I'd like to have generic method which returns default value for passed type, but for collection type I'd like to get empty collection instead of null, for example:
GetDefault<int[]>(); // returns empty array of int's
GetDefault<int>(); // returns 0
GetDefault<object>(); // returns null
GetDefault<IList<object>>(); // returns empty list of objects
The method I started to write is following:
public static T GetDefault<T>()
{
var type = typeof(T);
if(type.GetInterface("IEnumerable") != null))
{
//return empty collection
}
return default(T);
}
How to complete it ?
EDIT:
If anyone would like get default value of some type, based on type instance instead of type identifier, this construction below can be used, i.e.:
typeof(int[]).GetDefault();
The implementation is internally based on @280Z28 answer:
public static class TypeExtensions
{
public static object GetDefault(this Type t)
{
var type = typeof(Default<>).MakeGenericType(t);
var property = type.GetProperty("Value", BindingFlags.Static | BindingFlags.Public);
var getaccessor = property.GetGetMethod();
return getaccessor.Invoke(null, null);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…