Object creation fundamental [Resolved]

Posted by Akiii under C# on 5/9/2011 | Points: 10 | Views : 2590 | Status : [Member] | Replies : 6
Hi,

BaseClass baseClass = new DerivedClass();


Can anybody explain, what is the meaning of the above sample code ?

Thanks Regards
Akiii




Responses

Posted by: Ndebata on: 5/9/2011 [Member] Starter | Points: 50

Up
0
Down

Resolved
Hi
1. The object is of derived class as you have written new DerivedClass();
you can call the
baseClass.GetType()
method to see it.
This object has been type casted to that of a base class which will restrict the use to member/method of base class only.
lets say i have two classes as follows

public class MyBaseClass
{
public int BaseID { get; set; }
}
public class DerivedClass:MyBaseClass
{
public int DerivedID { get; set; }
}

and i am writing something like

MyBaseClass b = new DerivedClass { BaseID = 10, DerivedID = 20 };
Console.WriteLine(b.BaseID);
here i will only get BaseID, I can again typecast the same object to get DerivedID

DerivedClass d = b as DerivedClass;
Console.WriteLine(d.DerivedID);


Thanks,
Debata



Akiii, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ndebata on: 5/9/2011 [Member] Starter | Points: 25

Up
0
Down
Hi

By assigning a derived class instance to that of a base one ,will restrict the access of instance to the part that came from base calss to the derived.
http://msdn.microsoft.com/en-us/library/ms173149(v=vs.80).aspx
Thanks,
Debata

Akiii, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Akiii on: 5/9/2011 [Member] Bronze | Points: 25

Up
0
Down
hi ndebata......

Thanks for ur reply...

From the above, i have a few questions:-
(1) The object is of derived class or base class ?
(2) And it is casted to which type...?

I am little but confused regarding this casting...?
I have followed your link but it couldn't clear my doubts......

Thanks and Regards
Akiii

Akiii, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Akiii on: 5/9/2011 [Member] Bronze | Points: 25

Up
0
Down
Hi ndebata......

excellent description of the scenario....

So, we cannot call derived class members directly, first we have to typecast it to derived class then we can call it ?

Thanks and Regards
Akiii

Akiii, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ndebata on: 5/9/2011 [Member] Starter | Points: 25

Up
0
Down
yup :)

Regards,
Debata

Akiii, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Akiii on: 5/9/2011 [Member] Bronze | Points: 25

Up
0
Down
thanks ndebata.....

I am marking ur reply as answer....

Regards
Akiii

Akiii, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response