Is there any way to get sizeof()
a generic type? e.g.
public int GetSize<T>()
{
return sizeof(T); //this wont work because T isn't assigned but is there a way to do this
}
As said in the example, the above is not possible, but is there a way to make it work? Tried doing public unsafe int
but it didn't change anything. Really don't want to do something like
public int GetSize<T>()
{
if (typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte))
{
return 1;
}
else if (typeof(T) == typeof(short) || typeof(T) == typeof(ushort) || typeof(T) == typeof(char))
{
return 2;
}
//and so on.
}
You can use
Marshal.SizeOf(typeof(T));
Be very aware this is going to throw all sorts of unexpected results if you abuse it.
Maybe, you you could make the constraints on your generic method limit to Types
that will make sense to you, i.e int
, long
, ect
Also be wary of things like this Marshal.SizeoOf(typeof(char)) == 1.
Update
As MickD posted in his comments, (and unsurprisingly) the compiler Wizard Eric Lippert has made a blog post on some of the finer points
What’s the difference? sizeof and Marshal.SizeOf
Update
Also, as pointed out by MickD and to make it clear for any young Jedi
reading this Marshal.SizeOf
returns unmanaged size.
Marshal.SizeOf Method (Type)
Returns the size of an unmanaged type in bytes.
The size returned is the size of the unmanaged type. The unmanaged and managed sizes of an object can differ. For character types, the size is affected by the CharSet value applied to that class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With