value types vs reference types in c#

6
Value Types Vs Reference Types Like any programming language, C# defines a number of primitive keywords that represent basic data types. This data type can split up into two formats, they are a. Value based types(Memory allocated on Stack) b. Reference based types(Memory allocated on Heap) What are the Value Types and Reference Types? Value Types: All numeric data types (int, float, decimal, double, DateTime, Guid, Timespan, single and Boolean etc.,) as well as enumerations And Structures. Reference Types: String, Array, Delegate, Class and Exception etc. How data types are declared? Once you have declare the variable, .Net reserves a spot in memory for that variable, but it still has no value. If your are trying to use the variable without assigning a value, you would get an error from the Compiler. Complier will always force (warning message) you to assign some value to your variable. Why C# always force you to initialize the variable? Because this is for better memory management process. Value Type: Int i=0; // explicitly assign or initialize variable. Or int k = new int();

Upload: api-26344848

Post on 10-Apr-2015

841 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Value Types Vs Reference Types in C#

Value Types Vs Reference Types

Like any programming language, C# defines a number of primitive keywords that represent basic data types. This data type can split up into two formats, they are

a. Value based types(Memory allocated on Stack)b. Reference based types(Memory allocated on Heap)

What are the Value Types and Reference Types?

Value Types: All numeric data types (int, float, decimal, double, DateTime, Guid, Timespan,

single and Boolean etc.,) as well as enumerations And Structures.

Reference Types: String, Array, Delegate, Class and Exception etc.

How data types are declared?

Once you have declare the variable, .Net reserves a spot in memory for that variable, but it still has no value. If your are trying to use the variable without assigning a value, you would get an error from the Compiler. Complier will always force (warning message) you to assign some value to your variable.Why C# always force you to initialize the variable? Because this is for better memory management process.

Value Type:

Int i=0; // explicitly assign or initialize variable. Or

int k = new int();

Variable k will be consider as an object and Call default construtor to initialize variable. After that the object k is typecasted from object to integer datatype. So this is time taking process. So try to avoid using new Operator for value Types.

Reference Type:

ClassB clsb = new ClassB(); //Creating instance(object) for the ClassBpublic class ClassB{ int EmpNo; string EmpName;}

Page 2: Value Types Vs Reference Types in C#

What is the Type Allocated?

Value Types: Allocated on the stack. The stack is a simple first-in last-out memory structure, and is highly efficient. It has push and pop method. When a method is invoked, the CLR bookmarks the top of the stack. The method then pushes data onto the stack as it executes. When the method completes, the CLR just resets the stack to its previous bookmark “popping” all the method’s memory allocations is one simple operation!

public void SetValue(){ // i is pushed in to the stack by using Push Method.. int i = 20; Console.WriteLine(i.ToString());} // i is popped off the stack by using Pop Method

Reference Types:Allocated on the Managed Heap.CLR manages the Heap memory for reference type. Memory allocation for an object should be using the new keywords. Objects are allocated onto the managed heap, where they are automatically deallocated by the runtime at "Some time in the future”. Garbage collection is automated in C#. If the Managed heap does not have sufficient memory to allocate a requested object, a garbage collection will occur.

ClassB clsb = new ClassB();

How assigning values will behave?

Vaue Types:public void AssignDataToValueType(){ int i = 20; int j = i; Console.WriteLine(i); Console.WriteLine(j); j = 100; Console.WriteLine(i); Console.WriteLine(j);}i and j are value type variables. these variables are isolated form one another. In other words one variable value does not affect another. According to our eample i value does not change even if the j value is altered. Reference Types:CLassC clsobj1 = new CLassC();clsobj1.str = "Hai";CLassC clsobj2 = clsobj1;Console.WriteLine(clsobj1.str);Console.WriteLine(clsobj2.str);

Page 3: Value Types Vs Reference Types in C#

clsobj2.str = "Helo World";Console.WriteLine(clsobj1.str);Console.WriteLine(clsobj2.str);public class CLassC{ public string str; }clsobj1 and clsobj2 are two objects. While assigning one object to another mean two objects hold the same value.In out example if you change the value of clsobj2 the value of clsoobj1 will be changed automatically.

What is the Base Class?

Value Types: Value types are derived from System.Value; Reference Types:Reference Types are derived from System.Object;

How is a variable represented?

Value Types: Value type variables are local copies.

Reference Types:Reference type variables are pointing to the memory occupied by the allocated instance. That objects are available until a garbage collection collect the objects.

Can this type function as a base to other types?

Value Types: No. Values types are always sealed and cannot be extended.

Reference Types:Yes. If the type is not sealed it may function as a base to other types.

Default Parameters passing behavior?

Value Types: Variables are passed by value (i.e. a copy of the variable is passed into the called function)Reference Types:Variables are passed by reference (e.g. The address of the variable is passed into the called function.)

Able to override object.Finalize ()?

Value Types:

Page 4: Value Types Vs Reference Types in C#

No. Values types are never placed on to the heap and therefore do not need to be finalized.Reference Types:Yes indirectly.

Can I define constructors for this type?

Value Types: Yes. But the default constructor is reserved (your custom constructors must all have arguments)Reference Types: Yes When do variables of these types die?

Value Types: When it falls out of the defining scopeReference Types:When the managed heap calls the garbage collector to collect the object.

Page 5: Value Types Vs Reference Types in C#