Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, October 29, 2012

Boxing and Unboxing in C#

Boxing is the process of converting value type to the object type or to any interface type implemented by this value type. Whenever there is boxing the values are in the System.Object and the value is stored on the heap.

int i = 123;
object o = i; //boxing
 
Unboxing is the process where the value type is extracted from object.
 
o = 123;
i = (int)o; //unboxing

 
  

Thursday, October 25, 2012

Instance and Static Methods

The Static methods are the methods that have no instances. They are faster than the instance methods because they are called with the type name rather than the instance identifier. Static methods can be public or private. They can not use this instance expression.

This is a example to show the use of Static and Instance Methods

using System;
class Program
{
    static void StaticMethodA()
    {
        Console.WriteLine("Static method");
    }
    void InstanceMethodB()
    {
        Console.WriteLine("Instance method");
    }
    static char StaticMethodC()
    {
        Console.WriteLine("Static method");
        return 'C';
    }
    char InstanceMethodD()
    {
        Console.WriteLine("Instance method");
        return 'D';
    }
    static void Main()
    {
        // Call the two static methods on the Program type.
        Program.StaticMethodA();
        Console.WriteLine(Program.StaticMethodC());
        // Create a new Program instance and call the two instance methods.
        Program programInstance = new Program();
        programInstance.InstanceMethodB();
        Console.WriteLine(programInstance.InstanceMethodD());
        Console.ReadLine();
    }
}

Output :

Static method
Static method
C
Instance method
Instance method
D