Can you determine the size of the generic type?

Is there a way to get sizeof() generic type? eg.

 public int GetSize<T>() { return sizeof(T); //this wont work because T isn't assigned but is there a way to do this } 

As the example says, the above is not possible, but is there a way to make it work? I tried to do public unsafe int , but did not change anything. I 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. } 
+5
source share
1 answer

you can use

 Marshal.SizeOf(typeof(T)); 

Be very aware that this will cause all kinds of unexpected results if you abuse it.

Perhaps you could limit your limit to the generic Types method, which would make sense to you, i.e. int , long , ect

Also be careful with such things Marshal.SizeoOf(typeof(char)) == 1.

Update

As MickD posted in his comments (and not surprisingly), compiler master Eric Lippert made a blog post at some smaller points

What is the difference? sizeof and Marshal.SizeOf

Update

Also, as MickD pointed out, and to make it clear that any young Jedi reading this Marshal.SizeOf returns an unmanaged size.

Method (Type) Marshal .SizeOf

Returns the size of the unmanaged type in bytes.

The returned size is the size of the unmanaged type. Unmanaged and controllable dimensions of an object may vary. For character types, size depends on the CharSet value applied to this class.

+1
source

Source: https://habr.com/ru/post/1275801/


All Articles