I'm trying to make an extension method like this:
public static T Optional<T>(this T obj)
{
return obj != null ? obj : Activator.CreateInstance<T>();
}
However, it fails if there isn't a parameterless constructor for the type. Is there a way I can get an instance of an object without a parameterless constructor?
NOTE: I don't want to put where T : new()
and limit the method to only classes with parameterless constructors.