I have a class which pulls objects from Isolated Storage. If it cannot find the object in question it returns default(T) which would be null as they are reference types. If the value returned is null I do a simple check and assign a new instance in the caller but I would prefer to do this in the storage logic.
So my question, is there a way to return a new T where the object has a default blank constructor?
An option would be use the contraint “new”:
http://msdn.microsoft.com/en-us/library/sd2w2ew5(v=vs.80).aspx
Like so:
But having this constraint means that you can’t use a type that doesn’t have a default constructor. So you may consider to use System.Activator.CreateInstance, but remember that it may throw an exception:
So, it may be a good idea to know if the given type supports this early in the initialization, a way to do so follows:
While you are at it, why not get a delegate that creates an instance?
An example of how to use it (compiled with LinqPad):
The output is:
The case of string is a special case, being a referece type it can be null, and not having a public default constructor that’s what you get here instead of String.Empty. The nullable type also gives null.