How to determine the size of var?

Viewed 1571

I Have a variable declared as follows:

var a = 99494;

Then I used the following to determine the size of the variable in bytes:

Marshal.SizeOf(a)

Does it get the actual size of memory occupied by this value ?

2 Answers

Does it get the actual size of memory occupied by this value ?

Yes. In this case it is fairly simple, since the var is an int. It will always yield the same value (4). (var isn't a dynamic type, it is determined on compile time.)

Yes, var is just a compile time trick so the compiler will decide it's type at compile time. I wouldn't recommend using it besides obvious and very long class names. e.g var x = new BigBigBigClass(). It makes your code less readable to others and makes it easier to make mistakes. C# is a statically typed language and while it takes a few more seconds to declare types, it pays off when you aren't accidentally mixing classes

Since the compiler will put x as an int, it should return 32 bits (4 bytes) as that's the size of a standard int

Related