Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Getting size of a value-type variable at runtime?

I know languages such as C and C++ allow determining the size of data (structs, arrays, variables...) at runtime using sizeof() function. I tried that in C# and apparently it does not allow putting variables into the sizeof() function, but type defintions only (float, byte, Int32, uint, etc...), how am I supposed to do that?

Practically, I want this to happen:

int x; Console.WriteLine(sizeof(x));   // Output: 4 

AND NOT:

Console.WriteLine(sizeof(int)); // Output: 4 

I'm sure there's some normal way to get the size of data at runtime in C#, yet google didn't give much help.. Here it is my last hope

like image 480
Giora Ron Genender Avatar asked Nov 17 '11 19:11

Giora Ron Genender


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.


1 Answers

Following on from Cory's answer, if performance is important and you need to hit this code a lot then you could cache the size so that the dynamic method only needs to be built and executed once per type:

int x = 42; Console.WriteLine(Utils.SizeOf(x));    // Output: 4  // ...  public static class Utils {     public static int SizeOf<T>(T obj)     {         return SizeOfCache<T>.SizeOf;     }      private static class SizeOfCache<T>     {         public static readonly int SizeOf;          static SizeOfCache()         {             var dm = new DynamicMethod("func", typeof(int),                                        Type.EmptyTypes, typeof(Utils));              ILGenerator il = dm.GetILGenerator();             il.Emit(OpCodes.Sizeof, typeof(T));             il.Emit(OpCodes.Ret);              var func = (Func<int>)dm.CreateDelegate(typeof(Func<int>));             SizeOf = func();         }     } } 
like image 64
LukeH Avatar answered Oct 01 '22 14:10

LukeH