Created
September 26, 2023 04:46
-
-
Save tomohisa/1582f824540be1b78b953cb0d4282489 to your computer and use it in GitHub Desktop.
Create Default Instance from Type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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