C# sizeof() Operator: Use and Examples

In this tutorial, we will learn about the sizeof() operator in C#, its usage with examples. By IncludeHelp Last updated : April 06, 2023

C# sizeof() Operator

The sizeof() operator is used to get the size in bytes of compile-time known types, it does not work with the variables or instances.

Syntax

int sizeof(type);

It accepts the type and returns an int value – which is the size of that type in bytes.

Consider the below statements returning the sizes of the various types:

sizeof(char)    - 2
sizeof(int)     - 4
sizeof(long)    - 8

C# sizeof() Operator Example 1

In this program, we are getting and printing the size of various C# data types.

using System;
using System.Text;

namespace Test {
  class Program {
    static void Main(string[] args) {
      Console.WriteLine(sizeof(bool));
      Console.WriteLine(sizeof(byte));
      Console.WriteLine(sizeof(sbyte));
      Console.WriteLine(sizeof(char));
      Console.WriteLine(sizeof(short));
      Console.WriteLine(sizeof(ushort));
      Console.WriteLine(sizeof(int));
      Console.WriteLine(sizeof(uint));
      Console.WriteLine(sizeof(float));
      Console.WriteLine(sizeof(long));
      Console.WriteLine(sizeof(ulong));
      Console.WriteLine(sizeof(double));
      Console.WriteLine(sizeof(decimal));

      //hit ENTER to exit
      Console.ReadLine();
    }
  }
}

Output

1
1
1
2
2
2
4
4
4
8
8
8
16

C# sizeof() Operator Example 2

In this program, we are getting and printing the system type (using typeof() operator) and size of the various data types.

using System;
using System.Text;

namespace Test {
  class Program {
    static void Main(string[] args) {
      Console.WriteLine("size of {0} is {1} bytes", typeof (bool), sizeof(bool));
      Console.WriteLine("size of {0} is {1} bytes", typeof (byte), sizeof(byte));
      Console.WriteLine("size of {0} is {1} bytes", typeof (char), sizeof(char));
      Console.WriteLine("size of {0} is {1} bytes", typeof (UInt32), sizeof(UInt32));
      Console.WriteLine("size of {0} is {1} bytes", typeof (ulong), sizeof(ulong));
      Console.WriteLine("size of {0} is {1} bytes", typeof (decimal), sizeof(decimal));

      //hit ENTER to exit
      Console.ReadLine();
    }
  }
}

Output

size of System.Boolean is 1 bytes
size of System.Byte is 1 bytes
size of System.Char is 2 bytes
size of System.UInt32 is 4 bytes
size of System.UInt64 is 8 bytes
size of System.Decimal is 16 bytes



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.