How to get the sizeof a datatype in C#?

How to get the sizeof a datatype in C#?

How to get the sizeof a datatype in C#?

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.

Example: Convert string to int using Parse()

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;

namespace ConvertString
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(sizeof(int)); //returns 4
            Console.WriteLine(sizeof(char)); // returns 2
            Console.WriteLine(sizeof(bool));//returns 1
            Console.WriteLine(sizeof(long));//returns 8
            Console.WriteLine(sizeof(float));//returns 4
            Console.WriteLine(sizeof(double));//returns 8
            Console.WriteLine(sizeof(decimal));//returns 16
            
            Console.ReadLine();
        }
       
    }
}

Output:

Convert string to int using Parse

It can be used with the enum type, as shown below.

Example: sizeof with Enum

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')
All Comments