tags:

views:

149

answers:

3

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;
    }
}
+11  A: 

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.

Yuriy Faktorovich
If the class would have been static I would have understand. But since the object is passed by parameter, why doesn't it require to have accessor?
Daok
@Daok: Because your static method is a member of the class. If that static method was anywhere else it wouldn't be allowed.
Yuriy Faktorovich
Alright thanks for the precision.
Daok
Class members have access not only to members of any implicit `this` object, but they have access to members of any instance of that type that they have a reference to.
Michael Burr
It is lexical scoping. So anything defined in a particular class can access anything else defined in that class.
Eric Normand
If you add a class MySecondValue. And you change the Myvalue to have this method: public static implicit operator int(MySecondValue v) { return v.//No _myValue }You won't have access to _myvalue because it's private. This is why at first I thought it was weird because MyValue doesn't have public accessor. But if you told me that's because it's within the class that I can have access, I think it makes sense.
Daok
+5  A: 

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.

Stephen Doyle
+6  A: 

The private means private for the class and not private for the instance.

tpower
+1 -- Well said, precise, and pithy!
Nate Bross
+1 indeed: http://stackoverflow.com/questions/888224/what-is-your-longest-held-programming-assumption-that-turned-out-to-be-incorrect/888246#888246
Jeff Sternal
Hum, not private for the instance? I think it's wrong because I cannot use : Myvalue my = new Myvalue(100); my._Myvalue = 1; Because the instance "my" cannot access private variable.
Daok
@Daok - it's still private to the class, so my._myvalue isn't visible to external callers. To see this in action, add the following member to your Myvalue class: public int Test() { Myvalue my = new Myvalue(100); my._myvalue = 1; return my._myvalue; }. Then from Main, call new Console.WriteLine(Myvalue(1000).Test().ToString());
Jeff Sternal