Created
November 19, 2018 08:19
-
-
Save mjs3339/bd487ddeb6716d4e63bbb720850d2e0d to your computer and use it in GitHub Desktop.
C# Get Object Size
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 class GetObjectSize | |
{ | |
public enum SetValueEnum | |
{ | |
NotSet = -1, | |
Yes = 1, | |
No = 0 | |
} | |
private SetValueEnum _isPrimitive; | |
private int _primitiveSize; | |
private Type _type; | |
public int GetSize(object obj) | |
{ | |
if(_type == null) | |
_type = obj.GetType(); | |
if(_isPrimitive == SetValueEnum.NotSet) | |
_isPrimitive = IsValidPrimitive(_type) ? SetValueEnum.Yes : SetValueEnum.No; | |
if(_isPrimitive == SetValueEnum.Yes) | |
return _primitiveSize; | |
return Converters.GetBytesObject(obj, _type).Length; | |
} | |
public bool IsValidPrimitive(Type type) | |
{ | |
switch(Type.GetTypeCode(type)) | |
{ | |
case TypeCode.Boolean: | |
_primitiveSize = sizeof(bool); | |
return true; | |
case TypeCode.Char: | |
_primitiveSize = sizeof(char); | |
return true; | |
case TypeCode.SByte: | |
_primitiveSize = sizeof(sbyte); | |
return true; | |
case TypeCode.Byte: | |
_primitiveSize = sizeof(byte); | |
return true; | |
case TypeCode.Int16: | |
_primitiveSize = sizeof(short); | |
return true; | |
case TypeCode.UInt16: | |
_primitiveSize = sizeof(ushort); | |
return true; | |
case TypeCode.Int32: | |
_primitiveSize = sizeof(int); | |
return true; | |
case TypeCode.UInt32: | |
_primitiveSize = sizeof(uint); | |
return true; | |
case TypeCode.Single: | |
_primitiveSize = sizeof(float); | |
return true; | |
case TypeCode.Object: | |
return false; | |
case TypeCode.DateTime: | |
unsafe | |
{ | |
_primitiveSize = sizeof(DateTime); | |
} | |
return true; | |
case TypeCode.String: | |
return false; | |
case TypeCode.Int64: | |
_primitiveSize = sizeof(long); | |
return true; | |
case TypeCode.UInt64: | |
_primitiveSize = sizeof(ulong); | |
return true; | |
case TypeCode.Double: | |
_primitiveSize = sizeof(double); | |
return true; | |
case TypeCode.Decimal: | |
_primitiveSize = sizeof(decimal); | |
return true; | |
default: | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment