How to determine if an instance of a parent class was created from an instance of a specific child

I find it easier to ask this question through sample code.

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

If I were not connected with the above assignments, how would I determine if firstParent created from an instance of firstChild without accessing / comparing their fields or properties?

+5
source share
2 answers

Well, firstParent not created (the "new" keyword is not used), but is executed from firstChild :

 Parent firstParent = (Parent)firstChild; 

For testing using Object.ReferenceEquals (i.e. firstParent and firstChild are the same instance)

 if (Object.ReferenceEquals(firstParent, firstChild)) { ... } 
+9
source

a simple equality operator should work. if the Equals method is not overridden.

 Child firstChild = new Child(); Child secondChild = new Child(); Parent firstParent = (Parent) firstChild; Parent secondParent = (Parent) secondChild; Console.WriteLine(firstParent == firstChild); // true Console.WriteLine(firstParent == secondChild); // false 

Since the default equality method for objects is checked by reference

The standard Equals implementation supports reference equality for reference types and bitwise equality for value types. Link equality means that references to objects that are compared refer to the same object. Bitwise equality means that the objects being compared have the same binary representation.

0
source

All Articles