Skip to content

Instantly share code, notes, and snippets.

@SchreinerK
Created April 18, 2023 15:45
Show Gist options
  • Save SchreinerK/51ea4378f75f34134b6d93c5388c002e to your computer and use it in GitHub Desktop.
Save SchreinerK/51ea4378f75f34134b6d93c5388c002e to your computer and use it in GitHub Desktop.
Gets the default value for a Type.
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