Skip to content

Instantly share code, notes, and snippets.

@tomohisa
Created September 26, 2023 04:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomohisa/1582f824540be1b78b953cb0d4282489 to your computer and use it in GitHub Desktop.
Save tomohisa/1582f824540be1b78b953cb0d4282489 to your computer and use it in GitHub Desktop.
Create Default Instance from Type
public static class GeneralTypeExtensions
{
public static dynamic CreateDefaultInstance(this Type type)
{
if (type == typeof(string))
{
return "";
}
if (type == typeof(char[]))
{
return Array.Empty<char>();
}
if (type == typeof(short))
{
return 0;
}
if (type == typeof(int))
{
return 0;
}
if (type == typeof(uint))
{
return 0;
}
if (type == typeof(long))
{
return 0;
}
if (type == typeof(ulong))
{
return 0;
}
if (type == typeof(Guid))
{
return Guid.Empty;
}
var defaultConstructor = type.GetConstructor(Type.EmptyTypes);
if (defaultConstructor != null)
{
return Activator.CreateInstance(type) ?? "No default object found";
}
var firstConstructor = type.GetConstructors().FirstOrDefault();
if (firstConstructor != null)
{
var ctorParameters = firstConstructor.GetParameters();
var parameters = new object[ctorParameters.Length];
for (var i = 0; i < ctorParameters.Length; i++)
{
parameters[i] = CreateDefaultInstance(ctorParameters[i].ParameterType);
}
return firstConstructor.Invoke(parameters);
}
return "No default constructor found";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment