Reputation: 140993
How can this code compile? The code below in the operator int CAN access a private variable of the class MyValue? Why?
class Program
{
static void Main(string[] args)
{
Myvalue my = new Myvalue(100);
Console.WriteLine(my + 100);
Console.Read();
}
}
public class Myvalue
{
private int _myvalue;
public Myvalue(int value)
{
_myvalue = value;
}
public static implicit operator int(Myvalue v)
{
return v._myvalue;
}
}
Upvotes: 18
Views: 8276
Reputation: 56906
The private
means private for the class and not private for the instance.
Upvotes: 16
Reputation: 3744
operator int() is still a member function of the MyValue class and so can access all fields of objects of type MyValue.
Note that the static just means that a MyValue object needs to be passed to the function as a parameter.
Upvotes: 5
Reputation: 68737
Because it is in the class, it has access to private variables in it. Just like your instance public methods. It works the opposite way too. You can access private static members from instance members to create a Monostate pattern.
Upvotes: 20