Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Лаба №1 / books / csharp_ebook.pdf
Скачиваний:
51
Добавлен:
03.03.2016
Размер:
3.69 Mб
Скачать

Programmers Heaven: C# School

The new keyword

Suppose, in our Circle class, we don't want to override the Draw() method, but we need to have a Draw() method, what we can do? In Java, we can't do this. In C++, even if we mark the method in the base class as virtual, it is impossible. But, C# introduces a keyword new to mark a method as a non-overriding method and as the one which we don't want to use polymorphically. Let us define the Shape and Circle classes as:

class Shape

{

public virtual void Draw()

{

Console.WriteLine("Drawing Shape...");

}

}

class Circle : Shape

{

public new void Draw()

{

Console.WriteLine("Drawing Circle...");

}

}

Note that we marked the Draw() method in Circle with the new keyword to avoid polymorphism. In our method we write

Shape theShape = new Circle();

theShape.Draw();

When we compile and run the above code, we will see the following output:

Drawing Shape...

Since, we marked the Draw() method in the Circle class as new, no polymorphism is applied here and the Draw() method of the Shape class is called. If we don't mark the Draw() method with the new keyword, we will get the following warning at compile time:

'CSharpSchool.Circle.Draw()' hides inherited member

'CSharpSchool.Shape.Draw()'.

To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.

95

Programmers Heaven: C# School

Type casting the objects - Up-casting and Down-casting

Type Casting means 'making an object behave like' or 'changing the apparent type of an object'. In C#, you can cast an object in an inheritance hierarchy either from the bottom towards the top (up-casting) or from the top towards the bottom (down-casting).

Up-casting is simple, safe and implicit, as we have seen the reference of parent type can reference the object of child type.

Parent theParent = new Child();

On the contrary, down-casting is un-safe and explicit. By un-safe, we mean it may throw an exception – that is, fail. Consider the following line of code:

Shape [] shapes = { new Circle(), new Rectangle(), new Curve() };

Where Circle, Rectangle and Curve are sub-classes of Shape class. Now, if we want to reference the Rectangle object in the shapes array with the reference of type Rectangle, we can't just write

Rectangle rect = shapes[1];

Instead, we have to explicitly apply the cast here as

Rectangle rect = (Rectangle) shapes[1];

Since the cast is changing the apparent type of the object from parent to child (downward direction in inheritance hierarchy), it is called down-casting.

Also, note that down-casting can be unsuccessful and if we attempt to write

Rectangle rect = (Rectangle) shapes[2];

Since shapes[2] contains an object of type Curve which can not be casted to the Rectangle type, the CLR would raise the following exception at run-time:

System.InvalidCastException: Specified cast is not valid.

The is and as keywords

To check the run-time type of an object, you can use either the is or the as keyword. is compares the type of the object with the given type and returns true if it is cast-able; otherwise, it returns false. For example,

Console.WriteLine(shapes[1] is Rectangle);

96

Programmers Heaven: C# School

would print true on the Console Window, while

Console.WriteLine(shapes[2] is Rectangle);

would print false on the Console window. We might use the is operator to check the runtime type of an object before applying down-casting.

Shape [] shapes = { new Circle(), new Rectangle(), new Curve() };

Rectangle rect=null;

if(shapes[1] is Rectangle)

{

rect = (Rectangle) shapes[1];

}

Alternatively, we can also use the as operator to check the run-time type of the object. The as operator returns null if the object is not cast-able otherwise, it casts the object to the specified type as

Shape [] shapes = { new Circle(), new Rectangle(), new Curve() };

Rectangle rect = shapes[1] as Rectangle;

if(rect != null)

Console.WriteLine("Cast successful");

else

Console.WriteLine("Cast unsuccessful");

Although is and as perform similar functionality, is just checks the runtime type while as in addition to this, also casts the object to the specified type.

Boxing and Un-boxing

The last topic for today is boxing and un-boxing. Boxing allows value types to be implicitly treated like objects. Suppose, we have an integer variable i declared as

int i = 5;

when we write

i.ToString();

The Compiler implicitly creates an instance of the Object class and boxes (stores) a copy of this int value (5) in the object. It then calls the ToString() method on the instance of the Object class which has boxed the copy of the int value. It is similar to writing

97

Programmers Heaven: C# School

int i = 5;

Object obj = i;

// implicit boxing

obj.ToString();

You can see in the above code that boxing is implicitly applied in C# and you don't have to write

Object obj = (Object) i;

// unnecessary explicit boxing

 

 

On the other hand, un-boxing is explicit conversion from object type to value type. The following lines show how un-boxing is implemented in C#

int

i

= 5;

 

 

Object obj

= i;

// implicit boxing

int

j

= (int) obj;

// explicit un-boxing

 

 

 

 

 

Like down-casting, un-boxing can be un-safe and throw an InvalidCastException at runtime.

Author's Note: Although boxing and un-boxing look very similar to up-casting and down-casting, there are some points that differentiate the two:

Boxing and Un-boxing are the transformations between value type and object, while casting just transforms the apparent (reference) type of objects.

Value types are stored on the stack and objects are stored in the heap. Boxing takes a copy of the value type from the stack to the heap while un-boxing takes the value type back to the stack. On the other hand, casting does not physically move or operate on the object. Casting merely changes the way objects are treated in a program by altering their reference type.

98

Соседние файлы в папке books