Data Type in C#
As we know that C# is strongly typed computer language so we must declare the type of a variable that indicates the kind of values it is going to store eg. integer, float, string etc.
string stringVar = "Hello DotNet Palace!!"; int intVar = 10; float floatVar = 20.2f; char charVar = 'D'; bool boolVar = true;
Kinds of datatypes in C#
C# supports two kinds of data types: Value types and Reference types.
Value types
A data type is a value type if it holds a data value within its own memory space. It means the variables of these data types directly contain values. C# supports below kinds of datatypes of value type:
- bool
- byte
- char
- decimal
- double
- enum
- float
- int
- long
- sbyte
- short
- struct
- uint
- ulong
- ushort
When you pass a value-type variable from one method to another, the system creates a separate copy of a variable in another method. If value got changed in the one method, it wouldn't affect the variable in another method.
static void ChangeValue(int x) { x = 200; Console.WriteLine(x); } static void Main(string[] args) { int i = 100; Console.WriteLine(i); ChangeValue(i); Console.WriteLine(i); }
200
100
Reference types
Unlike value types, a reference type doesn't store its value directly. Instead, it stores the address where the value is being stored. In other words, a reference type contains a pointer to another memory location that holds the data.
static void ChangeReferenceType(Student std2) { std2.StudentName = "DotNet"; } static void Main(string[] args) { Student std1 = new Student(); std1.StudentName = "Palace"; ChangeReferenceType(std1); Console.WriteLine(std1.StudentName); }
- class
- string
- delegate
- Array
String is a reference type, but it is immutable. It means once we assigned a value, it cannot be changed. If we change a string value, then the compiler creates a new string object in the memory and point a variable to the new memory location. So, passing a string value to a function will create a new variable in the memory, and any change in the value in the function will not be reflected in the original value
The default value of a reference type variable is null
when they are not initialized. Null
means not refering to any object.
Summary
All the value types derive from System.ValueType
, which in-turn, derives from System.Object
. Click on next button for next tutorials.
Cheers!