Created
April 18, 2023 15:45
-
-
Save SchreinerK/51ea4378f75f34134b6d93c5388c002e to your computer and use it in GitHub Desktop.
Gets the default value for a Type.
This file contains 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 Utils { | |
public static object? Default(Type type) { | |
return Type.GetTypeCode(type) switch { | |
TypeCode.Boolean => false, | |
TypeCode.String => null, | |
TypeCode.Char => '\0', | |
TypeCode.SByte => (sbyte)0, TypeCode.Byte => (byte)0, TypeCode.Int16 => (short)0, | |
TypeCode.UInt16 => (ushort)0, TypeCode.Int32 => 0, TypeCode.UInt32 => (uint)0, | |
TypeCode.Int64 => (long)0, TypeCode.UInt64 => (ulong)0, | |
TypeCode.Single => 0.0f, TypeCode.Double => 0.0d, TypeCode.Decimal => 0m, | |
TypeCode.DateTime => DateTime.MinValue, | |
TypeCode.Empty => null, TypeCode.DBNull => null, | |
_ => type.IsClass ? null : Activator.CreateInstance(type) | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment