Personal Web & Sample Site
Skip Navigation Links
HOME |
About Me |
Articles
| Contact Us
C Sharp Part Three
Rating: 21 user(s) have rated this article Average rating: 5.0
Posted by: joet, on 10/1/2011, in category "C#"
Views: this article has been read 3589 times
Location: Houston, Tx, United States
Abstract: Now let talk about the System.Object class and what this has to do with Boxing and Unboxing a value. As you know a variable of type object can refer to any object of any reference type. However, variables of type object can also refer to a value type.

One of the most important reference types in in the Microsoft .NET Framework is the Object class in the System namespace.  This is the top of the food chain in .Net and requires you to fully understand inheritance ("is a" relationship).

INHERITENCE

The concept of class is useful because of its reusability; you can create new classes that are descendents of existing classes. The descendent classes (of child classes) can inherit all of the attributes of the original class (or parent class), or the descendent class can override those attributes that are inappropriate.

In geometry, a Cube is a descendent of a square. A Cube has all the attributes of a Square plus one more: depth. A Cube, however, has a different method of calculating a Cube's volume., you must also multiply by its height. In programming, if you have previously created a Square class and you need a Cube class, it makes sense to inherit features from the Square class, adding only the new feature (depth) that a Cube requires and modifying the method that calculates volume. That'll work for me!

Note: You can call a parent class a base class or superclass. You can refer to a child class as a derived class or subclass. NO! NOT ABSTRACT CLASS! SOMETHING ENTIRELY DIFFERENT!

KEY WORDS:

  • Abstract Class - A class that is created only to be a parent class and not to have objects of its own. You cannot instantiate an object using the "new" keyword from an abstract class.
  • Abstraction - The process of paying attention to important properties while ignoring nonessential details.You'll hear this often from other web developers describing a particular class or method.
  • Ambigous Method Call - A method call in which the compiler cannot determine which version of an overloaded method to execute.This means if you attempt to overload a method that has the same number of arguments in the list, and/or the same type, you will get a compile error.
  • Cardinality and Multiplicity - The arithmetic relationships between objects.
  • Polymorphism - A feature that allows the same operation to be carried out differently depending on the context.

If you don't understand inheritance you will run into problems understanding the following concepts. For now, if nothing else, simply accept that all classes are specialized types of the System.Object and that you can use System.Object to create a variable that can refer to any reference type. That said; let us move on to the following example.

In this example the variable C and O both refer to the same Circle object. The fact that the type of C is Circle and the type O is object (the alias for System.Object) in effect provides two different views of the same item in memory:

 

Example 1

 

Now, let us move on to the next concept:

BOXING

As you can see variables of type object can refer to any object of any reference type. However, variables of type object can also refer to a value type. So, for example if we have two statements, one initializes the varialbe i (of type int, a value type) to 42 and then we initialize the variable O (of type object, a reference type) to i:

int i = 42;

object O = i;

What is the value of O? This will not work. Remember that i is a value type and that it exists in the stack. If the reference inside O referred directly to i, the reference would refer to the stack and this is illegal. Reference types are created using memory from the heap and cannot reference the stack. So what the runtime does is automatically allocates a piece of memory from the heap, copies the value of integier i to this piece of memory, and then refers the object O to this copy. This automatic copying of an item from the stack to the heap is called boxing. The following graphic demonstrates the results.

Example 2

Note: Keep in mind that if you modify the original value of a variable, the value on the heap will not change. Likewise, if you modify the value on the heap, the original value of the variable will not change.

At this point you're probably thinking that you can get to the boxed value through the variable such as using a simple assignment statement like:

int i = O;

Guest what? This is not going to work. Consider what would happen in the following code if this statement were allowed:

Circle c = new Circle();

int i = 42;

object = o;

 

o = c; // o refers to a Circle

i = o; // what is stored in i?

To obtain the value of the boxed copy, you must use what is known as a cast, an operation that checks whether it is safe to convert one type to another and then does the conversion. You prefix the object variable with the name of the type in parentheses, as in this exampe:

int i = 42;

object o = i; // boxes

i = (int)o; // compiles okay

The effect of the cast is subtle. However, if o does not refer to a boxed int, there is a type mismatch, causing the cast to fail. The compiler-generated code throws an InvalidCastException at run time. Here is an example of an unboxing cast that fails:

Circle c = new Circle(42);

object o = c; // doesn't box because Circle is a reference variable.

int i = (int)o; / compiles okay but throws an exception at run time.

CASTING DATA SAFELY

By using a cast, you can specify that, in your opinion, the data referenced by an object has a specific type and that it is safe to reference the object by using that type. The key phrase here is "in your opinion." If the type of object in memory does not match the cast, the runtime will throw an "InvalidCastException".

EXCEPTIONS

Catching an exception and attempting to recover in the event that a type of an object is not what you expected it to be is a rather cumbersome approach. C# provides two more ver useful operators that can help you perform casting in a much more elegant manner, the is and as operators.

The is Operator:

WrappedInt wi = new WrappedInt();

....

object o = wi;

if (0 is WrappedInt)

     {

          WrappedInt     temp     =     (WrappedInt)o;  // This is safe: o is a WrappedInt

          .....

     }

The as Operator:

WrappedInt     wi     =     new     WrappedInt();

...

object o = wi;

WrappedInt     temp     =     o    as     WrappedInt;

if     (temp     !=    null)

.....     // Cast was successful

This is actually used on my site when accessing profiles from the business class. In order to access the user's profile from a business class, or from the page base class, you access it through the Profile property exposed by the current HttpContext. The HttpContext class is the container for the current web request - it's used to pass around objects that are part of the request: forms, properties, ViewState, etc. Anytime you process a page, you will have this HttpContext information, so you can always pull a Profile class instance out of the HttpContext class. The return type is ProfileBase, though, not the ProfileCommon object generated on-the-fly that enabled you to use IntelliSense and access properties in a strongly-typed manner. Therefore, the resulting Profile class instance read from the HttpContext.Current.Profile will not be strongly typed. No problem - just do the cast and you are ready to use the profile as usual. Individual properties of the profile will be strongly typed, as expected. The following snippet show an example of this:

ProfileCommon profile = HttpContext.Current.Profile as ProfileCommon;

profile.BirthDate = new DateTime(1963, 09, 10);

Done!

I will add more to the article at a later date!

 


How would you rate this article?

User Feedback

Post your comment
Name:
E-mail:
Comment:
Insert Cancel

Copyright © 2013 Jose M. Tamez
Last Updated August 18th 2013