How do I new T()?

  • Thread starter Thread starter Brett Romero
  • Start date Start date
B

Brett Romero

I'd like to do this:

public class myclass<T>
{
myclass()
{}

public void CreateNew()
{
T myp = new T();
}
}

However, I get this compiler error:
Cannot create an instance of the variable type 'T' because it does not
have the new() constraint

I may type the class as Person. This means I want to create a new
Person object when CreateNew is called. Is there a way to do this?

Thanks,
Brett
 
I don't think this is possible but is there a way to get generic enough
that I can do:

//contructor
public Collection ( int personId )
{
T p = default(T) ( personId );
this.Add ( p.PersonId, p );
}

So that my type T knows ahead of time what it may be dealing with. I
may also have Employee types with e.employeeId or Customer types with
c.customerId. The code may go to:

public Collection ( int entityId )
{
T e = default(T) ( entityId );
this.Add ( e.?Id, p );
}

I know T doesn't know ahead of time but is there another way to go
about doing it similar to that. I don't want to handle each specific
case or use switches and conditionals to check the type.

Thanks,
Brett
 
Brett Romero said:
I'd like to do this:

public class myclass<T>
{
myclass()
{}

public void CreateNew()
{
T myp = new T();
}
}

However, I get this compiler error:
Cannot create an instance of the variable type 'T' because it does not
have the new() constraint

I may type the class as Person. This means I want to create a new
Person object when CreateNew is called. Is there a way to do this?

As the compiler suggests, you need a new() constraint, which means you
can only use types with a public parameterless constructor as the type
parameter:

public class MyClass<T> where T : new()
{
MyClass()
{
}

public void CreateNew()
{
T myType = new T();
}
}

Note that you can't specify parameters in constructor constraints - a
public parameterless one is all you can specify.
 
Let's say I'm creating my own collection class. Where as before I was
passing in an ID that would belong to the new Person object for
example, I can still make use of the parameterless constructor and
also assign the ID by:

MyClass<Person> mycollection = new MyClass<Person>();
mycollection.AssignIDOnLastEntry = personid;

I just have MyClass create a new type of T object in its constructor
and do away with the CreateNew() method. I might create a new indexer
that always returns the last entry so I can be sure to not overwrite a
Person object that has state. Or as above, just assign the Person
object ID to a property that assigns it to the last created Person
object in an internal list. Comments?

Thanks,
Brett
 
The problem here is the same. At compile time, I can't create
predicates that assign e.personid because T doesn't have that property
available.

Brett
 
Why dont you make an interface and implement that in your class and add the
interface to the constraints list like this:

interface IMyinterface
{
string Name
{
get;
set;
}

}

class test1<T> where T : IMyinterface, new()
{
public test1 ()
{

}

public void CreateNew ()
{
T n= new T();
n.Name = "Jon";

}

}
U can set your props now.

I hope this works for u.

regards,

Ab.
 
Brett Romero said:
The problem here is the same. At compile time, I can't create
predicates that assign e.personid because T doesn't have that property
available.

In that case, you should add that as a constraint, by way of an
interface - create an interface with everything you know you need (such
as PersonId) and make a "T : IPerson" constraint.

I don't particularly like your idea of having a property on a
collection which changes the contents of whichever person was added
last though - that doesn't sound like the right way to go. That
person's ID isn't in itself really a property of the collection.
 
I'm doing it this way because when I drop in a known PersonId into the
collection, I want a Person object created with that PersonId. I let
the collection do it. So, I may read in 2000 PersonIds from a
datareader and create them on the fly. Now I have access to all of
them.

I agree that having the object properties within the collection is not
so great. The collection should be a container only of those objects.
I can still access the object's properties via indexers but those are
the actual object properties and do not belong to the collection. How
would you initialize the Person, etc objects in that case? I'm
thinking you would drop the PersonId into a new() Person object. Then
add that new object to the collection. Now the collection is not
responsible for creating/destroying its objects.

Thanks,
Brett
 
I have no idea why nobody has pointed out that all you need is a constructor
constraint:

public class myclass<T> where T : new()
 
Brett Romero said:
I'm doing it this way because when I drop in a known PersonId into the
collection, I want a Person object created with that PersonId. I let
the collection do it. So, I may read in 2000 PersonIds from a
datareader and create them on the fly. Now I have access to all of
them.

I agree that having the object properties within the collection is not
so great. The collection should be a container only of those objects.
I can still access the object's properties via indexers but those are
the actual object properties and do not belong to the collection. How
would you initialize the Person, etc objects in that case? I'm
thinking you would drop the PersonId into a new() Person object. Then
add that new object to the collection. Now the collection is not
responsible for creating/destroying its objects.

I'm not sure what you mean by "drop the PersonId" to start with, I'm
afraid - but I'd certainly need to look at a larger part of the design
before really suggesting anything, I'm afraid.
 
Mind if I ping you privately or do you want me to post in the group?
The question basically centers around what is good design for this
scenario.

Thanks,
Brett
 
Brett Romero said:
Mind if I ping you privately or do you want me to post in the group?
The question basically centers around what is good design for this
scenario.

I'm generally in favour of keeping things public, just because someone
else is likely to come across the same situation - and other people are
likely to have better ideas than me, too! If you want to mail me
privately, however, you're more than welcome to.
 
I agree in posting it here for learning. I just wasn't sure if we were
going in a direction people aren't interested in...but here goes...

By drop the PersonId, I meant to pass it into the collection's
constructor. The constructor will create a new Person object (via
typed T) and add that to its .List (since the collection has inherited
Dictionary<>).

The more important design issues are:
1.) Should I have one collection through out the app or strive for one
collection and type it against the objects I'll use in various
scenarios?

The argument for one collection is it will be a simple implementation
and greatly decrease overall complexity. It simple holds typed objects
and I don't need collections for every type of object.

2.) Also, should the collection be simple and really not worry about
the objects in it?

If Person objects have an address collection (since a person can have
multiple addresses) in them, should I have a FillAddresses() method on
the collection that lazy loads all of its Person.FillAddress()'s? Or
should I instead loop through the collection and access FillAddresses()
off of each Person object. For example:
for(int i; i < mycollection.count; i++)
mycollection.FillAddress();

instead of mycollection.FillAddresses();

Just in general, what are you thoughts on keeping the two structures
very independent of each other? Fundamentally, the fewer nodes in a
system, the less complex the system. By adding specific object
behavior to the collection (i.e. FillAddresses()), it touches the
objects its holding and worse creates specific cases (Employee objects
may need a fill YTD hours worked method in the collection). Ultimately
a node is extended in the system and complexity increased.

Thanks,
Brett
 
Brett Romero said:
I agree in posting it here for learning. I just wasn't sure if we were
going in a direction people aren't interested in...but here goes...

<snip>

Just to say - I don't have time to write a full answer now, but will
try to do so over the weekend. Things are a touch hectic at the
moment...
 
Brett Romero wrote:

If Person objects have an address collection (since a person can have
multiple addresses) in them, should I have a FillAddresses() method on
the collection that lazy loads all of its Person.FillAddress()'s? Or
should I instead loop through the collection and access FillAddresses()
off of each Person object. For example:
for(int i; i < mycollection.count; i++)
mycollection.FillAddress();


A problem with this approach is that it transferres control back and
forth between the looping code and the collection. This is undesireable
if mycollection is a remote object or FillAddresses does lookups with
high expense on indvidual actions, compared to grouped ones -- as
database lookups.
instead of mycollection.FillAddresses();

This is chunky, and resolves the problem above, it does however
introduce the problem that you have to fill all addresses, and it binds
the code that fill the address to the collection, which probably
shouldn't have any idea of to lookup address'es in it's constituent objects.

This problem crops up again and again, and the best solution i've seen
is to introduce a separate protocol, for example:

public delegate void PersonCallback(Person p);
public interface IAddressFiller {
// If address isn't found
// if notfound == null
// throw
// else
// invoke notfound(p).
// to abort filling programatically in notfound, throw
void FillAddress(Person p, PersonCallback notfound);
void FillAddresses(ICollection<Person> persons,
PersonCallback notfound);
}

And have an implementation of that protocol that fits the situations,
for example if addresses are to be filled from a database:

public class DataBaseAddressFiller {
public readonly DatabaseReferenceOrWhatnot Data;
...
public void FillAddress(Person p, AddressFillError error) {
// lookup person p
Address a = lookup_single_address(p);
if ( address_not_found )
if ( error == null )
throw new AddressNotFoundException(p);
else
error(p);
}
public void FillAddress(ICollection<Person> persons,
AddressFillError error) {
ICollection<Result> results;
if ( persons.Count < Data.PersonsCount() * factor )
results = parametrised_select_addresses(persons);
else
results = select_addrdesses();
// set addresses,
// You can utilize ORDER_BY and sorting, or a dictionary
// to pair up persons and results
// if a person is missing an address:
if ( address_not_found )
if ( error == null )
throw new AddressNotFoundException(p);
else
error(p);
}
}

If you need to indicate progress, you can let the IAddressFiller
functions accept a callback for each success as well as failure.

You may also wish to extend the PersonCallback with some EventArgs, if
specific failure info needs to be passed up.
 
Brett Romero said:
I agree in posting it here for learning. I just wasn't sure if we were
going in a direction people aren't interested in...but here goes...

Finally finding time to address this...
By drop the PersonId, I meant to pass it into the collection's
constructor. The constructor will create a new Person object (via
typed T) and add that to its .List (since the collection has inherited
Dictionary<>).

So your *constructor* takes the ID of the first person for the list?
That seems slightly unusual in itself.
The more important design issues are:
1.) Should I have one collection through out the app or strive for one
collection and type it against the objects I'll use in various
scenarios?

The argument for one collection is it will be a simple implementation
and greatly decrease overall complexity. It simple holds typed objects
and I don't need collections for every type of object.

It will depend on what else your collection does - if it needs to do
something with the objects which depends on them implementing a certain
interface, for instance, then that means you won't be able to use it
for other types of objects.
2.) Also, should the collection be simple and really not worry about
the objects in it?

If Person objects have an address collection (since a person can have
multiple addresses) in them, should I have a FillAddresses() method on
the collection that lazy loads all of its Person.FillAddress()'s? Or
should I instead loop through the collection and access FillAddresses()
off of each Person object. For example:
for(int i; i < mycollection.count; i++)
mycollection.FillAddress();

instead of mycollection.FillAddresses();


The former is certainly more flexible - although using a foreach loop
would make it even simpler.
Just in general, what are you thoughts on keeping the two structures
very independent of each other? Fundamentally, the fewer nodes in a
system, the less complex the system. By adding specific object
behavior to the collection (i.e. FillAddresses()), it touches the
objects its holding and worse creates specific cases (Employee objects
may need a fill YTD hours worked method in the collection). Ultimately
a node is extended in the system and complexity increased.

Yes. I'd only consider adding specific functionality to the collection
if it really applies to the collection itself.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top