473,404 Members | 2,174 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

How do I new T()?

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

Mar 19 '06 #1
19 13512
Ahhg! Thank you.

Brett

Mar 19 '06 #3
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

Mar 19 '06 #4
Alexander van Doormalen <av*********@gmail.com> wrote:
T myp = default(T);


No, that will return null if T is a class, or 0/false/'0' etc
otherwise.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 19 '06 #5
Brett Romero <ac*****@cygen.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 19 '06 #6
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

Mar 19 '06 #7
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

Mar 20 '06 #8
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" <ac*****@cygen.com> wrote in message
news:11**********************@t31g2000cwb.googlegr oups.com...
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

Mar 20 '06 #9
Brett Romero <ac*****@cygen.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 20 '06 #10
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

Mar 20 '06 #11
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" <ac*****@cygen.com> wrote in message
news:11**********************@g10g2000cwb.googlegr oups.com...
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

Mar 20 '06 #12
This was done by Jon six threads back.

Brett

Mar 20 '06 #13
Brett Romero <ac*****@cygen.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 20 '06 #14
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

Mar 20 '06 #15
Brett Romero <ac*****@cygen.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 20 '06 #16
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[i].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

Mar 21 '06 #17
Brett Romero <ac*****@cygen.com> wrote:
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...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 22 '06 #18


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[i].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.

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Mar 23 '06 #19
Brett Romero <ac*****@cygen.com> wrote:
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[i].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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 25 '06 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: William C. White | last post by:
Does anyone know of a way to use PHP /w Authorize.net AIM without using cURL? Our website is hosted on a shared drive and the webhost company doesn't installed additional software (such as cURL)...
2
by: Albert Ahtenberg | last post by:
Hello, I don't know if it is only me but I was sure that header("Location:url") redirects the browser instantly to URL, or at least stops the execution of the code. But appearantely it continues...
3
by: James | last post by:
Hi, I have a form with 2 fields. 'A' 'B' The user completes one of the fields and the form is submitted. On the results page I want to run a query, but this will change subject to which...
0
by: Ollivier Robert | last post by:
Hello, I'm trying to link PHP with Oracle 9.2.0/OCI8 with gcc 3.2.3 on a Solaris9 system. The link succeeds but everytime I try to run php, I get a SEGV from inside the libcnltsh.so library. ...
1
by: Richard Galli | last post by:
I want viewers to compare state laws on a single subject. Imagine a three-column table with a drop-down box on the top. A viewer selects a state from the list, and that state's text fills the...
4
by: Albert Ahtenberg | last post by:
Hello, I have two questions. 1. When the user presses the back button and returns to a form he filled the form is reseted. How do I leave there the values he inserted? 2. When the...
1
by: inderjit S Gabrie | last post by:
Hi all Here is the scenerio ...is it possibly to do this... i am getting valid course dates output on to a web which i have designed ....all is okay so far , look at the following web url ...
2
by: Jack | last post by:
Hi All, What is the PHP equivilent of Oracle bind variables in a SQL statement, e.g. select x from y where z=:parameter Which in asp/jsp would be followed by some statements to bind a value...
3
by: Sandwick | last post by:
I am trying to change the size of a drawing so they are all 3x3. the script below is what i was trying to use to cut it in half ... I get errors. I can display the normal picture but not the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.