Home > other >  C# Check if two generic variables point to same element
C# Check if two generic variables point to same element

Time:11-24

I have two variables that both have the same generic type T. Is there a way to check if both variables point to the same variable?

Eg.: I have a Person class and have two independent variables: Person peter and Person jack. My T is set to Person. The check I want to do should return true if T variableA and T variableB are both set to peter and should return false if T variableA is set to peter and T variableB is set to jack.

CodePudding user response:

You can use Object.ReferenceEquals

Person peter = new Person{ Name = "Peter" };
Person jack = peter;
bool sameReference = Object.ReferenceEquals(peter, jack); // true
  • Related