upcasting

  • Thread starter Thread starter juli jul
  • Start date Start date
J

juli jul

Hello,
I did the following with Class A which is a parent and B inherits from
it:
B b1=new B();
A a1=new A();
a1=b1;
Is it an upcasting in c#?
Thank you!
 
public class Employee
{

}

public class Programmer: Employee
{

}

OKAY
=====
Employee e = new Programmer(); // boxing
Programmer p = (Programmer)e; // unboxing

WRONG
=======
Programmer p = new Employee(); // wrong because not every employee is a
programmer
 
Brandon Driesen said:
public class Employee
{

}

public class Programmer: Employee
{

}

OKAY
=====
Employee e = new Programmer(); // boxing
Programmer p = (Programmer)e; // unboxing

Actually, boxing has nothign to do with this, since you are working with
classes. The first is an example of basic OO concepts, a Programmer is-a
Employee, thus can be treated as one. The second is a cast which tells the
compiler that you want e treated as a Programmer explicitly and are aware
that if it is not an exception will occur.

Boxing is the way the runtime treats value types(your standard int, char,
byte data types plus any struct or enum) as an object with virtual method
tables and the whole bit. Since value types do not have the object header
that is used to call virtual methods(such as interface methods and
ToString()), the sync block structure used by the lock keyword(and the
Montior class), among other things, you can't do something like "object o =
10" because the value 10 is just 4 bytes containing the bit pattern for the
number 10, it lacks all of the specifics of objects. Boxing gets around this
by copying the value and type information into a full reference type object
that can be treated like any other object. It is comparatively expensive
since it means copying your value and probably several times the size of
your value due to the added memory taken by the object header.

An actual example of boxing would be something like...

int unboxed = 10;
object boxed = unboxed; //boxing occurs here.
unboxed = (int)boxed; //unboxing occurs here.
 
Hi,

Nop, that is regular polimorphism.

The problem is when you have this:

B b1=new B();
A a1=new A();
A a2=new A();
B b2;

a1=b1; // succesful ,a B instance is assignable to an A instance
b2 = (B) a1; // this is succesful, as a1 DOES has a reference to a B
instance
b2 = (B) a2; // Exception, a2 DOES NOT HAS an isntance of B

Where you see this more often is with collections ( ArrayList , etc ) as
they keep a reference to object that you need to cast ( the 2do case ) to
the correct type.

cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top