Ishraq Ahmad
Blog for .net Architects & Developers looking to learn WPF, Silverlight, WCF and ASP.net MVC.
Reference Type and Value Type
Common Language Runtime is based on two types which are Reference Type and Value Type. Let’s take a brief look into each of one.
Reference Type
Most of Microsoft .net framework classes are reference types. So, what Reference Type is exactly?
It is a type which is always allocated from the managed heap.
You need to use C# new keyword to allocate them. This “new” keyword returns memory address of this reference type object.
Most of people don’t know that declaring a reference type could force garbage collection to occur. As a programmer you should always prefer to use Value type over Reference types. All classes are Reference types like System.Exception, System.Random and they inherit from System.Object.
Value Type
It is type which is always allocated on thread’s stack.
The instance or variable contains the value rather than holding pointer to an instance. Most people get confused with enum and consider them reference type which is wrong. Structures and Enumerations are always value types, for example, System.Int, System.Boolean.
Important thing to note that all Value types are sealed which prevent them from being used as base type. In simple words, you cannot define a new type using Char, Int32 and Decimal etc. By default, C# compiler initializes value types by zero.
Related posts:
Tags: ASP.net, C#, Reference Type, System.Object, Value Type