Patrick Desjardins
Patrick Desjardins

Reputation: 140993

Accessing private member of a parameter within a Static method?

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

Answers (3)

tpower
tpower

Reputation: 56906

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

Upvotes: 16

Stephen Doyle
Stephen Doyle

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

Yuriy Faktorovich
Yuriy Faktorovich

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

Related Questions