How to use C# sizeof operator to find out the size of a type

Using sizeof operator

To obtain this information, use the sizeof operator.

Syntax

It has this general form:

sizeof(type)

Example

Example for sizeof operator


using System;// w w w.jav a  2s . c o  m
using System.Globalization;

struct MyValueType
{
  public short s;
  public int i;
  public long l;
}


public class MainClass{

  static void Main(string[] args)
  {
    Console.WriteLine("sizeof operations");
    unsafe
    {
      Console.WriteLine("The size of short is {0}", sizeof(short));
      Console.WriteLine("The size of int is {0}", sizeof(int));
      Console.WriteLine("The size of long is {0}", sizeof(long));
      Console.WriteLine("The size of MyValueType is {0}\n", sizeof(MyValueType));
    }
  }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    C# Language »




C# Hello World
C# Operators
C# Statements
C# Exception