Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge
  • All
  • C#
  • MVC
  • Web API
  • Azure
  • IIS
  • JavaScript
  • Angular
  • Node.js
  • Java
  • Python
  • SQL Server
  • SEO
  • Entrepreneur
  • Productivity

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()
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
Try it

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.

Example: Invalid sizeof Usage
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')
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.