Click here to Skip to main content
15,908,901 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
class A
{
}
class B :A
{
}
class Prog
{
Static void main()
{
A a=new A();
B b=new B();
a=b;
b=a;
}
}


can we assign the objects like dis.
Posted
Updated 14-Dec-12 20:10pm
v2
Comments
[no name] 15-Dec-12 2:11am    
What your are up to ?

Yes, you can, but you need to understand clearly what happens. No new object is created by such assignment.

As the type is class, which is a reference type, you end up having two different references to the same object, which is, of course, often needed. A new object is only created with a constructor. Even if there is no constructors, and the object is created using some factory method, internally it is still created via a constructor, with heap memory allocation.

You need to read on value and reference types.

Good luck,
—SA
 
Share this answer
 
v2
Hi,

According to your code I don't think it is possible. It is not possible because Visual Studio will give a compile error at b=a;. The reason is A is the parent class and the B is the child class. So compiler works according to the rule of 'No parent object can assigned to a child object". But vice-verse is possible. But you can overcome this compile error by casting as,
b = (B)a;
For this scenario this works because at the previous line you have assigned as
a = b
These classes are reference types, so after
a = b
'a' is actually a B class instance. If you remove the
a = b
then a run time exception will be throwed as
System.InvalidCastException
with the message
Unable to cast object of type 'A' to type 'B'


Regards.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900