3
Reply

[solved] scope of private variables

Ask a question
This code works. I'm not sure it should. It's a standard overwriting of the Equals method. The part that puzzles me is the field 'unitId'. It's a *private* field.

That 'this.unitId' works is no mystery. It's part of the same object. But why doesn't the 'otherTUI.unitId' give a compilation error, let alone work ? It belongs to another (hence 'otherTUI) instantiated object and it is 'private' ? Should it not be out of scope ?

Does the act of casting make it come into scope '(TransportUnitInfo) obj'?

public class TransportUnitInfo
{
private int unitId;

public override bool Equals (object obj)
{

/*
if (obj == null)
return false;

if (!this.GetType().Equals(obj.GetType()))
return false;
*/

TransportUnitInfo otherTUI = (TransportUnitInfo) obj;
return this.unitId == otherTUI.unitId;
}
}

Commented out boilerplate, to not let it distract, it needs to be there but thats not what I'm wondering about.


Answers (3)