Understanding Data Types in C#

C# is the strongly typed programming language which means it enforces the strict restriction on intermixing the value with different data types.

Unlike JavaScript, In C# it is compulsory to define the variable with one of the data types.Data types in C# is mainly divided into three categories.

  1. Value Type
  2. Reference Type

Value Type

int, long, byte, char, float, bool etc are the Value Type data types. These data types hold the values directly which means, when you declare a string as,

string name=”Hello BuzzedCode”;

then, the .Net Framework allocates the memory to store the value “Hello BuzzedCode” on the variable “name” of data type “string“.

Value types are non-nullable type by default which means they cannot be assigned with null value until you make them nullable explicitly.

To make them nullable you can use “?” sign.

Reference Type

string, object, dynamic, class, interface etc are the Reference Type data types. They do not store the data directly in a variable instead they contain the reference (address) to the variable.

The reference hold the address of the variable rather than the data itself.

When you assign the Reference Type data types variable to another, it does not copy the data.Instead, it pass the address of the variable.

Reference types are nullable type which means they can be assigned with null value. The default value for the reference type is null.

Difference between Value Type and Reference Type

  • Value Type are stored on stack but Reference Type are stored on heap.
  • Value Type store the real data but Reference Type store the reference to the data.
  • Value Types can not contain the null value but Reference Type can be nullable.
  • The required namespace for Value Type is System.ValueType but for Reference Type is System.Object.

About dipneupane

Dip is a passionate Software Developer based in Kathmandu, Nepal. He chew code and smash keyboard for living. Apart from that, he writes about almost everything on buzzedcode.com.

View all posts by dipneupane →

Leave a Reply

Your email address will not be published. Required fields are marked *