Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if an instance of a parent class was created from an instance of a particular child

Tags:

c#

I find it easier to ask this question through a code example.

class Parent {}
class Child : Parent {}
...
...
Child firstChild = new Child();
Child secondChild = new Child();
Parent firstParent = (Parent)firstChild;
Parent secondParent = (Parent)secondChild;

If I wasn't privy to the above assignments, how would I determine if firstParent was created from the instance firstChild without accessing/comparing their fields or properties?

like image 779
digital_fate Avatar asked Sep 10 '15 09:09

digital_fate


People also ask

Is an instance of a child class also an instance of the parent class?

'No', it is an instance of the Child class, not of the Parent.

Can a parent class inherit from a child class?

Inheritance concept is to inherit properties from one class to another but not vice versa. But since parent class reference variable points to sub class objects. So it is possible to access child class properties by parent class object if only the down casting is allowed or possible....

Can a parent class be a child class?

No, you can not do. This is because any instance of ClassB is also an instance of ClassA but vice versa is not true. Additionally if above statement is not clear, Unless there's a good reason, it is better to avoid the situation where parent class is dependent on child class. Save this answer.

Does Instanceof check for inheritance?

The instanceof operator. It returns true if obj belongs to the Class or a class inheriting from it. Please note that arr also belongs to the Object class.


1 Answers

Well, firstParent is not created (there is no "new" keyword being used) but cast from the firstChild:

Parent firstParent = (Parent)firstChild;

To test use Object.ReferenceEquals (i.e. firstParent and firstChild are just the same instance)

if (Object.ReferenceEquals(firstParent, firstChild)) { ... }
like image 175
Dmitry Bychenko Avatar answered Oct 12 '22 08:10

Dmitry Bychenko