Sunday, July 31, 2011

Boxing and Unboxing in .Net

Contents are from MSDN.

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system, in which a value of any type can be treated as an object.
In the following example, the integer variable i is boxed and assigned to object o.

int i = 123;
// The following line boxes i.
object o = i; 


The object o can then be unboxed and assigned to integer variable i:

o = 123;
i = (int)o;  // unboxing


The following examples illustrate how boxing is used in C#.

// String.Concat example.
// String.Concat has many versions. Rest the mouse pointer on
// Concat in the following statement to verify that the version
// that is used here takes three object arguments. Both 42 and
// true must be boxed.
Console.WriteLine(String.Concat("Answer", 42, true));


// List example.
// Create a list of objects to hold a heterogeneous collection
// of elements.
List<object> mixedList = new List<object>();

// Add a string element to the list.
mixedList.Add("First Group:");

// Add some integers to the list.
for (int j = 1; j < 5; j++)
{
    // Rest the mouse pointer over j to verify that you are adding
    // an int to a list of objects. Each element j is boxed when
    // you add j to mixedList.
    mixedList.Add(j);
}

// Add another string and more integers.
mixedList.Add("Second Group:");
for (int j = 5; j < 10; j++)
{
    mixedList.Add(j);
}

// Display the elements in the list. Declare the loop variable by
// using var, so that the compiler assigns its type.
foreach (var item in mixedList)
{
    // Rest the mouse pointer over item to verify that the elements
    // of mixedList are objects.
    Console.WriteLine(item);
}

// The following loop sums the squares of the first group of boxed
// integers in mixedList. The list elements are objects, and cannot
// be multiplied or added to the sum until they are unboxed. The
// unboxing must be done explicitly.
var sum = 0;
for (var j = 1; j < 5; j++)
{
    // The following statement causes a compiler error: Operator
    // '*' cannot be applied to operands of type 'object' and
    // 'object'.
    //sum += mixedList[j] * mixedList[j]);

    // After the list elements are unboxed, the computation does
    // not cause a compiler error.
    sum += (int)mixedList[j] * (int)mixedList[j];
}

// The sum displayed is 30, the sum of 1 + 4 + 9 + 16.
Console.WriteLine("Sum: " + sum);

// Output:
// Answer42True
// First Group:
// 1
// 2
// 3
// 4
// Second Group:
// 5
// 6
// 7
// 8
// 9
// Sum: 30
  


In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, a new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally. For more information, see Performance.



Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object.
Consider the following declaration of a value-type variable:

int i = 123; 

The following statement implicitly applies the boxing operation on the variable i:

// Boxing copies the value of i into object o.
object o = i;   

The result of this statement is creating an object reference o, on the stack, that references a value of the type int, on the heap. This value is a copy of the value-type value assigned to the variable i. The difference between the two variables, i and o, is illustrated in the following figure.
Boxing Conversion

It also possible to perform the boxing explicitly as in the following example, but explicit boxing is never required:

int i = 123;
object o = (object)i;  // explicit boxing




This example converts an integer variable i to an object o by using boxing. Then, the value stored in the variable i is changed from 123 to 456. The example shows that the original value type and the boxed object use separate memory locations, and therefore can store different values.




class TestBoxing
{
    static void Main()
    {
        int i = 123;

        // Boxing copies the value of i into object o.
        object o = i; 

        // Change the value of i.
        i = 456; 

        // The change in i does not effect the value stored in o.
        System.Console.WriteLine("The value-type value = {0}", i);
        System.Console.WriteLine("The object-type value = {0}", o);
    }
}
/* Output:
    The value-type value = 456
    The object-type value = 123
*/


The following example demonstrates a case of invalid unboxing and the resulting InvalidCastException. Using try and catch, an error message is displayed when the error occurs.

class TestUnboxing
{
    static void Main()
    {
        int i = 123;
        object o = i;  // implicit boxing

        try
        {
            int j = (short)o;  // attempt to unbox

            System.Console.WriteLine("Unboxing OK.");
        }
        catch (System.InvalidCastException e)
        {
            System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);
        }
    }
}


This program outputs:
Specified cast is not valid. Error: Incorrect unboxing.
If you change the statement:
int j = (short) o;
to:
int j = (int) o;
the conversion will be performed, and you will get the output:
Unboxing OK.



Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:
·         Checking the object instance to make sure that it is a boxed value of the given value type.
·         Copying the value from the instance into the value-type variable.
The following statements demonstrate both boxing and unboxing operations:
int i = 123;      // a value type
object o = i;     // boxing
int j = (int)o;   // unboxing


The following figure demonstrates the result of the previous statements.
Unboxing Conversion

For the unboxing of value types to succeed at run time, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type. Attempting to unbox null causes a NullReferenceException. Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.

Enjoy Have a nice day.

Saturday, July 30, 2011

What are Static Constructors and how Static Constructors are invoked?

Static Constructors: A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
Static constructors have the following properties:
  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
Example :-


OUTPUT of above code :


NOTE : Static Constructors doesn't take any Access Modifier. This is rule. By default is private.

    class A
    {
        /// <summary>
        /// Static Constructors doesn't take any Access Modifier. This is rule.
        /// </summary>
        static A()
        {
            Console.WriteLine("A : Static Constructor.");
        }

       /// <summary>
        /// Default Constructor
        /// </summary>
        public A()
        {
            Console.WriteLine("A : Default Constructor.");
        }
    }

When we have static constructors in our class then it would be called first.
There can be several scenarios with static constructors.

1.       If we have static and default constructors in same class then first Static constructor would be called then Default.
2.       If we have three classes A,B,C have static constructors and are inherited in such a way C:B:A, then constructors would be invoked in following sequence :-
a.       Default Constructors would be called in A:B:C sequence. Rule is, first base class default constructor will call then derived class default constructor.
b.      Static Constructors would be called in C:B:A sequence. (Opposite to invocation of Default Constructors.). Rule is, first derived class static constructor will be called then base class static constructor.

Here is the example of the same.
Making object of class C all constructors would get invoked. First all static constructors then default constructors.


Hence we can say that :-
1.       For static constructor : First derived class static constructor will be called then base class static constructor.
2.       For default constructor : First base class default constructor will call then derived class default constructor.

Another example: 




Friday, July 29, 2011

What are association, aggregation and composition in OOPs?

Association

Association is a relationship where all object have their own life cycle and there is no owner. Let’s take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers but there is no ownership between the objects and both have their own life cycle. Both can create and delete independently.
Points:
  • Is a Relationship between objects.
  • Objects have independent life cycles.
  • There is no owner.
  • Objects can create and delete independently.

Aggregation

Aggregation is a specialize form of Association where all object have their own life cycle but there is ownership and child object cannot belongs to another parent object. Let’s take an example of Department and teacher. A single teacher cannot belongs to multiple departments, but if we delete the department teacher object will not destroy. We can think about “has-a” relationship.
Points:
  • Specialize form of Association.
  • has-a relationship between objects
  • Object have independent life-cycles
  • Parent-Child relationship

On the other hand aggregation relation just represents reference between classes. For example consider Employee and contact information. Blow diagram represents the UML



The above UML describes Aggregation relation which mentions that Employee refers to Address. And life time of Address is not managed by Employee. It is like "Employee has a Address". Let us see how it can be implemented in C#.

public class Address
{
 . . .
}

public class Employee

{

     private Address address;

     public Employee(Address address)

     {

         this.address = address;

     }

     . . .

}

Composition

Composition is again specialize form of Aggregation. It is a strong type of Aggregation. Child object does not have their life cycle and if parent object deletes all child object will also be deleted. Let’s take again an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room cannot belongs to two different house if we delete the house room will automatically delete. Let’s take another example relationship between Questions and options. Single questions can have multiple options and option cannot belong to multiple questions. If we delete questions options will automatically delete.
Points:
  • Specialize form of Aggregation.
  • Strong Type of Aggregation.
  • Parent-Child relationship.
  • Only parent object has independent life-cycle.

Lets take a simple example of Cycle. Cycle should contain 2 tyres and if we convert it to logical model below is the UML diagram




The above UML describes that Cycle contains 2 Tyres and the life time of each Tyre is maintained by Cycle. It is like "Tyre is Part Of Cycle". Let us see how it can be implemented in C#.

public class Tyre
{
 . . .
}

public class Cycle

{

    Tyre[] tires = new Tyre[]{new Tyre(), new Tyre()};

    .......

}

Have a grate day.

Encapsulation vs abstractions

“Abstraction and encapsulation are not synomous,” says P.J. Plauger in Programming on Purpose.



Encapsulation is information hiding. In other words: "Information hiding allows for implementation of a feature to change without affecting other parts that are depending on it.”
Encapsulation is a process where you group all data and methods (way to process data) together under an umbrella. This is a kind of normalization that we do on the object and its behavior.
Also, Encapsulation can be defined as the procedure of packing data and operations that operate on them into a single entity. This means that to access data, certain predetermined methods should be used. In other words, the data contained are not directly accessible. This ensures that data integrity is preserved because the user is unable to directly approach and modify the data as he / she wants. Users will receive or will the data values ​​only by methods that are publicly available to users.


Abstraction: Look at it as “what” the method or a module does not “how” it does it.
Definition: “The notion abstraction is to distill a complicated system down to its most fundamental parts and describe these parts in a simple, precise language.”
Abstraction is the way to hide complex implementation from outer world. For example: List.Sort() will sort the list and will give back the sorted list. User need not to worry about what algorithm the Sort() function has used. Object oriented programming/language offers this kind of abstraction.
Abstraction is the process of separating the details of presentation of the implementation details. This is done so that the developer is relieved of the complex details about implementation. The programmer can instead concentrate on the presentation or details of behavior of the entity. In simple terms, the abstraction focuses how a certain entity can be used rather than how it is executed. The abstraction hides the implementation details essentially, that even if the implementation methodology completely changes the time, the programmer should not worry how it would affect his program.

·         Encapsulation protects abstraction.
·         Encapsulation is the bodyguard, Abstraction is the VIP.
S.No.
Abstraction
Encapsulation
1
VIP
Assistant
2
Technically abstraction is like use of methods in a class by creating an object of that class, and u no need to know how the these methods are defined and worked
Encapsulation keeps code and data, it manipulates, safe from the outside code, i.e. it work like a wrapper for the inside code.
3
Abstraction is showing only essential details.
Encapsulation is hiding the working of abstraction in a class or template
4
Example:
A real world example, consider u have setup a big building(say a company), the details regarding materials used to build (glass, bricks), type of work, manager of the company, number of floors, design of the building, cost of the building etc. can be classified as ABSTRACTION.
Whereas, type of glass or bricks (grey one or red one) used, who all work for which all departments n how they work, cost of each and every element in the building etc. comes under Data ENCAPSULATION.
5
Outer layout, used in terms of design.
Inner layout, used in terms of implementation.
6
Abstraction provides business value; encapsulation "protects" these abstractions. If a developer provides a good abstraction, users won't be tempted to peek at the object's internal mechanisms. Encapsulation is simply a safety feature.
Encapsulation provides the explicit boundary between an object's abstract interface (its abstraction) and its internal implementation details.
7
In order to process something from the real world we have to extract the essential characteristics of that object.

Data abstraction can be viewed as the process of refining away the unimportant details of an object, so that only the useful characteristics that define it remain. Evidently, this is task specific.
Encapsulation is one step beyond abstraction. Whilst abstraction involves reducing a real world entity to its essential defining characteristics, encapsulation extends this idea by also modeling and linking the functionality of that entity. Encapsulation links the data to the operations that can be performed upon the data.

Abstraction has the methods which will be common for all the derived class would need. It contains the skeleton which needs to be implemented by the derived class also, which will be declared as abstract method.

Example:

abstract class CurryBase
{
public abstract void doCurryMasala();
}

public class FishCurry : CurryBase
{
public void doCurryMasala()
{
// Add Fish Curry specific contents also.
}
}
Encapsulation is basically, wrapping up of data members and methods.
As you said, You hide the data for security such as making the variables as private, and expose the property to access the private data which would be public. So, when you access the property you can validate the data and set it.

Example:

Class Demo
{
private int _mark;

public int Mark
{
get { return _mark; }
set { if (_mark > 0) _mark = value; else _mark = 0; }
}
}

Have a nice day ahead.