Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you determine the size of a generic type?

Tags:

c#

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.
}
like image 951
Asdar Avatar asked Mar 09 '18 02:03

Asdar


1 Answers

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.

like image 80
TheGeneral Avatar answered Nov 15 '22 23:11

TheGeneral