How to print the size of various data types in C#

Overview

The size of a data type is the size it takes in memory. Their sizes vary. This size is represented in bytes. We can use the sizeof() method to get their sizes.

Syntax

sizeof(datatype)
syntax for sizeof() method in C#

Parameters

datatype: This is the datatype whose size we want to get in memory.

Return value

The value returned is the size of a data type in memory.

Example

using System;
class DatatypeSize
{
static void Main()
{
// print sizes of some datatypes
Console.WriteLine("sizeof(int): {0}", sizeof(int)); // 4
Console.WriteLine("sizeof(float): {0}", sizeof(float)); // 4
Console.WriteLine("sizeof(char): {0}", sizeof(char)); // 2
Console.WriteLine("sizeof(double): {0}", sizeof(double)); // 8
Console.WriteLine("sizeof(bool): {0}", sizeof(bool)); // 1
}
}

Explanation

  • Lines 7–11: We get the sizes of some data types in memory using the sizeof() method. Then we print the results to the console.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources