Sunday, March 1, 2009

Boxing Unboxing in C#

All types in c# are derived from the System.Object base class. In .NET languages, there are basically two types:

1. Value type (derived from System.ValueType) - The struct and primitive types are stored on the stack (very fast accessible memory area)
2. Reference type (derived from System.Object) - the object types are stored on the heap (in case of .NET its managed heap)

The conversion of value type to reference type is known as boxing and converting reference type back to the value type is known as unboxing.

class Test
{
static void Main()
{
int i = 1;
object o = i; // boxing

int j = (int) o; // unboxing

}
}

BOXING:

Converting a value type to reference type is called Boxing. When a variable of a value type needs to be converted to a reference type, an object box is allocated to hold the value, and the value is copied into the box.

UNBOXING:

Converting a reference type back to it's value type is called un-boxing. When an object box is cast back to its original value type, the value is copied out of the box and into the appropriate storage location.

You cannot Implicitly convert a reference type to a value type. Unboxing is an explicit operation. E.g., if a variable x is boxed as Int32 variable, then it must be unboxed to Int32 variable. So, the type the variable uses to box will remain the same when unboxing the same variable.

Note: In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, an entirely new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally.

Actually when a value type is boxed, an entirely new object must be created. This can take up to 20 times longer than an assignment. When unboxing, the casting process can take four times as long as an assignment.

C# Property

In C#, properties are nothing but natural extension of data fields. They are usually known as ‘smart fields’ in C# community.

Properties provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

The significance of these properties is its usability. These properties need not be called with any function names like objectname.get or objectname.set etc., But they can be directly assigned the values or retrieve the values.

// private member variable
private int hour;

// public property
public int Hour
{
get { return hour; }
set { hour = value; }
}

Where access modifier can be private, public, protected or internal.

Languages that don't have properties will use methods (functions or procedures) for encapsultation. The idea is to manage the values inside of the object, state, avoiding corruption and misuse by calling code.

Features:

-> Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.
-> A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels.
-> The set accessor has a free variable available in it called value, which gets created automatically by the compiler. We can't declare any variable with the name value inside the set accessor.
-> A property should have at least one accessor, either set or get.
-> Since normal data fields and properties are stored in the same memory space, in C#, it is not possible to declare a field and property with the same name.
-> You can add a property to a C# class using a code wizard in Class View only. Adding a property using the C# Property Wizard adds a property stub body to the class's .cs file, which you can then edit.
-> Properties can be made read-only. This is accomplished by having only a get accessor in the property implementation.
-> You can assign values to, but not read from, a write-only property. A write-only property only has a set accessor.

Static Properties: C# supports static properties, which belongs to the class rather than to the objects of the class. All the rules applicable to a static member are applicable to static properties also. Remember that set/get accessor of static property can access only other static members of the class. Also static properties are invoking by using the class name.

Properties & Inheritance: The properties of a Base class can be inherited to a Derived class. The inheritance of properties is just like inheritance any other member.

Properties & Polymorphism: A Base class property can be polymorphicaly overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level.

Properties & Abstractions: A property inside a class can be declared as abstract by using the keyword abstract. Remember that an abstract property in a class carries no code at all. The get/set accessors are simply represented with a semicolon. In the derived class we must implement both set and get assessors. If the abstract class contains only set accessor, we can implement only set in the derived class.

Auto-Implemented Properties:

This is where a property encapsulates a property with get and set accessors, without any other logic is common. It is more code than we should have to write for such a common scenario. That's why C# 3.0 introduced a new syntax for a property, called an auto-implemented property, which allows you to create properties without get and set accessor implementations.

public class Customer
{
public int ID { get; set; }
public string Name { get; set; }
}


In an auto-implemented property, the C# compiler creates the backing store field behind the scenes, giving the same logic that exists with traditional properties, but saving you from having to use all of the syntax of the traditional property.

Practical benefits of properties:

There are times when you could use non-private fields. However, there are still benefits to using properties even for trivial situations:

-> There's more fine-grained access control with properties. Need it to be publicly gettable but really only want it set with protected access? No problem (from C# 2 onwards, at least).
-> Want to break into the debugger whenever the value changes? Just add a breakpoint in the setter.
-> Want to log all access? Just add logging to the getter.
-> Properties are used for data binding in (WinForms and WPF); fields aren't.
-> In case you are designing a class library and the consumer is not under your control then add properties for all public fields to prepare for future needs to add checks to field access.
-> In case you can version (change) the client code as well, do not add properties just because its good, or because you think you might need functionality of checks, lazy loading in the future. In case you do not need these features right-away allow clients to directly use fields. With the new re factoring features of VS2005 changing all references to the field to properties is a non-issue.
-> With the above two filtering you are sure that once you have a property its definitely going to do some additional work and so only use the property from everywhere (including methods from same class).