The last sentence from Marc Gravell's answer (emphasis mine)
...unless you wanted to do something obscure like not using a constructor
at all (which can be done)
and from this comment of his, there is an alternative to achieve the same thing. I don't much know which is better performance wise, but honestly, I don't care. If you want to know, follow that link. There author shows a hybrid way.
Use System.Runtime.Serialization.FormatterServices.GetUninitializedObject()
(old MSDN documentation link).
public static T SomeMethod<T>()
{
if (typeof(T) == typeof(string))
{
return default(T);
}
return (T)FormatterServices.GetUninitializedObject(typeof(T));
}
Note the special care for string
. Without that GetUninitializedObject()
would fail. This is from MSDN on using this approach on strings:
It does not create an uninitialized string, since creating an empty
instance of an immutable type serves no purpose.
It says nothing about why it fails, but more about why it should fail. Immediately after this there is another Note which goes like this:
You cannot use the GetUninitializedObject method to create instances
of types that derive from the ContextBoundObject class.