Sunday, June 12, 2016

CSharp Data Types

Data Types in C#

C# is a strongly typed language. This means every variable you declare has a type associated to it. The types specifies the size and location of memory. The types available in C# are simple (a.k.a value) types and reference types.

Simple Types or Value Types

Value types are variables that are based on System.ValueType. These types actually contains the value in them. They are the boxes that keep the value inside the box. If the type of variable is any one of the built-in data types like int, char, string and so on, then that value of that variable will be stored on a stack which is a highly efficient memory.

C# Value or Simple Types

Name Size Range (Min - Max)
byte 8 bit integer (Unsigned) 0 to 255
sbyte 8 bit integer (Signed) -128 to 127
char 16 bit (Unicode) U+0000 to U+FFFF
int 32 bit integer (Signed) -2,147,483,648 to 2,147,483,647
uint 32 bit integer (Unsigned) 0 to 4,294,967,295
long 64 bit integer (Signed) –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulong 64 bit integer (Unsigned) 0 to 18,446,744,073,709,551,615
short 16 bit integer (Signed) -32,768 to 32,767
ushort 16 bit integer (Unsigned) 0 to 65,535
double 15 to 16 digits precision ±5.0 × 10−324 to ±1.7 × 10308
decimal 28-29 significant digits (-7.9 x 1028 to 7.9 x 1028) / (100 to 28)
float 7 digits precision -3.4 × 1038to +3.4 × 1038
bool Boolean value true or false

C# Reference Types

Unlike value types that contain the value within them, reference types are variable whose value is a memory address. This memory address may actually point to the value stored on the heap.

Reference types are also called complex types in that you define it by combining one or more of the built-in or other reference types.

Complex types derive from Object type which is the base class for all reference types. We will look at Object Oriented Principles later in the series.

Reference types are housed in a heap memory and requires a non deterministic approach for memory management like garbage collection.

To put it simply, if you have an object of type Cat and you name it Daisy, here Daisy is a pointer to a place in the heap which contains the data for a type Cat. Lets look at an example.

public class Cat {
    public string name {get; set;}
    public string colour {get; set;}
}

The above code defines a Cat type with two attribute name and colour.

Cat daisy = new Daisy();
daisy.name = "Daisy Jr'";
daisy.age = 4;

The above 3 lines creates a Cat object whose reference name is daisy. This reference points to an object with two string values on the heap. If you create another Cat named kitty and assign the it daisy, then daisy and kitty will point to the same memory location on the heap.

 In simple words, reference types refer to something on the heap whereas a value types occupies its place on a stack.

No comments:

Post a Comment