archimedes
archimedes

Reputation:

Is there a simple way to determine type size in C#?

Is there a way to say something like:

sizeof(type)? Or type.Size?

Right now I am looking at using code like:

if (type.Equals(typeof(int)))
    return sizeof(int);
else if (type.Equals(typeof(long)))
    return sizeof(long);

etc, etc, for every single data type.

There must be an cleaner solution, no?

Upvotes: 7

Views: 12903

Answers (4)

Stupid Girl
Stupid Girl

Reputation: 9

Maybe you can go Convert.ToString(type.MaxValue, 2).Length / 8 ?

Upvotes: -4

JaredPar
JaredPar

Reputation: 755557

Try Marshal.SizeOf()

http://msdn.microsoft.com/en-us/library/5s4920fa.aspx

Upvotes: 12

Daniel Schaffer
Daniel Schaffer

Reputation: 57872

If this is for data access, you can do type.GetTypeCode() (which is a member of IConvertible), which gives you a nice enum to switch on.

Upvotes: 1

Related Questions