Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing private member of a parameter within a Static method?

Tags:

c#

.net

.net-2.0

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;
    }
}
like image 997
Patrick Desjardins Avatar asked Oct 27 '09 14:10

Patrick Desjardins


People also ask

Can static method access private member?

DR; TL; Yes it can.

How do you access private static members?

The usual solution is to use a static member function to access the private static variable. A static member function is like a static member variable in that you can invoke it without an object being involved. Regular member functions can only be applied to an object and have the hidden "this" parameter.

Can static methods access private members java?

Yes, we can have private methods or private static methods in an interface in Java 9. We can use these methods to remove the code redundancy. Private methods can be useful or accessible only within that interface only. We can't access or inherit private methods from one interface to another interface or class.

Can static methods call private methods?

Your public/default static methods can still call your private statics.


1 Answers

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.

like image 177
Yuriy Faktorovich Avatar answered Sep 29 '22 18:09

Yuriy Faktorovich