I keep wanting to know if two variables are pointing at the same instance of a class. Sounds obvious, but can it be done?
For example. Imagine you have the following code with an operator called “IsSameInstanceAs”. Is there any way of fulfilling the logic of the “IsSameInstanceAs” operator as stated in the comments inside the if statements using .Net, C#:-
public class MyClass
{
public String MyString;
public static void TestForSameInstance()
{
MyClass myInstanceA = new MyClass();
MyClass myInstanceB = myInstanceA;
MyClass myInstanceC = new MyClass();
myInstanceA.MyString = "A String";
myInstanceC.MyString = myInstanceA.MyString;
if (myInstanceA IsSameInstanceAs myInstanceB)
{
// These are the same instance so they will match and this if is true
}
if (myInstanceA IsSameInstanceAs myInstanceC)
{
// These are not the same instance so they will not match and this if is false
}
}
}
I believe this cannot be done, but if anyone knows better then please help. Remember, I do not want to compare object instances, I want to know if they are the same instance.
John Thompson
Object.ReferenceEquals is the relevant method.