Alex Rivera | Logout

Accessing private member of a parameter within a Static method?

Asked 2009-10-27T14:16:23.460
18

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;
    }
}
Edit
Report

1 Answer

5

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.

answered 2009-10-27T14:20:11.250

Your Answer