Reputation: 145
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.
}
Upvotes: 9
Views: 2706
Reputation: 81493
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
, etc.
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.
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.
Upvotes: 6