sdbps (10) [Avatar] Offline
#1
Hi,

I was just reading page 180 which discusses the constructor constraint with the following example:

public T CreateInstance<T>() where T : new()
{
return new T();
}

Next, the book states "CreateInstance<int>();...[is] ok." I thought I found a bug, as an int is a value type, but then I tried it out in VS 2010 and IntelliSense showed that int was a "reference" to Int32, which was an object wrapper for int. I was aware of Int32, but I didn't realize you could use it in this way.

I think I've got it - am I correct ?

Thanks,

Scott
sdbps (10) [Avatar] Offline
#2
Re: Value type not really a value type in constructor type constraint examp
Oops. It's actually page 77 in the hard copy of the book...it's page 180 in Adobe...duh.

Scott
mgravell (64) [Avatar] Offline
#3
Re: Value type not really a value type in constructor type constraint example ?
It is an *alias*, not a reference; int === System.Int32.

All value-types implicitly (in C#, at least) qualify as having a public parameterless constructor, so they are fine with " : new()". For example, you can also write:

int i = new int();

which is identical to either:

int j = default(int);
int k = 0;

If the example said ": class" (which doesn't mean class, but means reference-type) it would fail.

Re intellisense - for me is says it *represents* a 32-bit signed integer; it doesn't mention "reference".

Message was edited by:
mgravell
sdbps (10) [Avatar] Offline
#4
Re: Value type not really a value type in constructor type constraint examp
Hi,

Thanks for your reply. Yeah, I know reference was the wrong description; thanks for suggesting alias/represents. Thanks for the explanation, too.

Scott