In C#, the sizeof operator returns a number of bytes that would be allocated by the common language runtime in managed memory.
For example, the following returns the sizeof an integer type.
sizeof(int); //returns 4
sizeof(char); // returns 2
sizeof(bool);//returns 1
sizeof(long); //returns 8
sizeof(float); //returns 4
sizeof(double);//returns 8
sizeof(decimal);//returns 16
It can be used with the enum type, as shown below:
public struct Point
{
public Point(byte tag, double x, double y) => (Tag, X, Y) = (tag, x, y);
public byte Tag { get; }
public double X { get; }
public double Y { get; }
}
Sizeof(Point); // returns 24
however, the sizeof operator cannot determine the size of a variable.
int i = 10;
sizeof(i);// compilation error: 'i' does not have a predefined size, therefore sizeof can only be used in an unsafe context
sizeof(string);//compilation error: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string')
Related Articles
- Difference between String and StringBuilder in C#
- Static vs Singleton in C#
- Difference between == and Equals() Method in C#
- Asynchronous programming with async, await, Task in C#
- How to loop through an enum in C#?
- Generate Random Numbers in C#
- Difference between Two Dates in C#
- Convert int to enum in C#
- BigInteger Data Type in C#
- Convert String to Enum in C#
- Convert an Object to JSON in C#
- Convert JSON String to Object in C#
- DateTime Formats in C#
- How to convert date object to string in C#?
- Compare strings in C#
- How to count elements in C# array?
- Difference between String and string in C#.
- How to get a comma separated string from an array in C#?
- Boxing and Unboxing in C#
- How to convert string to int in C#?