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
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 ...
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.
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.
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(); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With