Monday, July 27, 2009

Sometimes I amaze even myself!

I built a generic method in C#. One of the parameters to the method was the generic type <T>

Looking at my method, I created some instances of T using the new keyword/operator.

I thought to myself, "some classes don't have a constructor... I'll need to restrict that in the declaration. Something like
private static long CreateInstances<T>(List<T> instanceCollection) where T "has a default constructor" {...}


I looked up the where contextual keyword and learned that the syntax for what I wanted to do was:
private static long CreateInstances<T>(List<T> instanceCollection) where T: new() {...}


Just before I hit that last parenthesis I noticed the red-squiggle. It was under some code down in the method body that used the type 'T'

T variable = new T();


I hovered over the squiggled text to see what was the matter:
Error: Cannot create an instance of the variable type 'T' because it does not have the new() constraint.


Ha!! I defeated the red-squiggle before I had even seen it!

Thursday, July 23, 2009

Experiments!

I wasn't sure if the C# is operator would throw a null-reference exception if I gave it a null object. (Katie, a null object is simply an empty placeholder - think of someone's name in your address book, but without an address. When you try to mail them something, you wouldn't just send a blank envelope to them, you're smart enough to recognize the "address not found exception". Null-reference exception is the same thing.)

So, I built an experiment:

static void Main(string[] args)
{
object foo = new System.Xml.XmlDocument();
object bar = null;
System.Uri zap = new Uri("http://fake.uri.nategrigg.com");

try {
Console.WriteLine("foo.GetType(): {0}", foo.GetType().ToString());
Console.WriteLine("foo: {0}", foo.ToString());
Console.WriteLine("bar: null");
Console.WriteLine("zap.GetType(): {0}", zap.GetType().ToString());
Console.WriteLine("zap: {0}", zap.ToString());
Console.WriteLine("foo is object: {0}", foo is object);
Console.WriteLine("bar is object: {0}", bar is object);
Console.WriteLine("zap is object: {0}", zap is object);
Console.WriteLine("foo is XmlDocument: {0}", foo is System.Xml.XmlDocument);
Console.WriteLine("zap is Uri: {0}", zap is Uri);
Console.WriteLine("bar = zap");
bar = zap;
Console.WriteLine("bar is Uri: {0}", bar is Uri);
} catch ( NullReferenceException nullex ) {
Console.WriteLine("Null reference exception: {0}", nullex.Message);
}

Console.ReadKey();
}


Conclusion: When given a null variable, the is operator simply returns false. Which is just what I needed!

Also, the program had the following output (in case you're curious):

foo.GetType(): System.Xml.XmlDocument
foo: System.Xml.XmlDocument
bar: null
zap.GetType(): System.Uri
zap: http://fake.uri.nategrigg.com/
foo is object: True
bar is object: False
zap is object: True
foo is XmlDocument: True
zap is Uri: True
bar = zap
bar is Uri: True