Daniel Camacho
Daniel Camacho

Reputation: 423

How to declare/set a static variable inside a method

I cannot get/set a static variable inside a method. How can I do it?

    public class LoginDialog
{
    // class members

    private static string _user=""  ;

    public  void RunDialog()
    {

        _user = "Peter";

    }

    public static string _User { get; set; }

}

After reading the answers I edit my code and I cant still get the static variable _user. What I am doing wrong?

    public class LoginDialog
{   
    private static string _user;  

    public void RunDialog()
    {
       LoginDialog._user = "Peter";
    }
    public static string _User { get {return _user;}  }
}

When I declare like that everything works fine, but rather I would like to declare inside the method.

 private static string _user="Peter";

Upvotes: 4

Views: 65054

Answers (1)

phoog
phoog

Reputation: 43046

The problem is that you're setting a private static field, and then presumably reading the public static property elsewhere. In your code, the public static property is completely independent of the private static field.

Try this:

public class LoginDialog 
{ 
    // class members
    public  void RunDialog() 
    {
        _User = "Peter";
    }

    public static string _User { get; private set; } 
} 

The property _User creates its own invisible private backing field, which is why it is entirely separate from the private _user field you declared elsewhere.

(Style guidelines dictate the name User for the public static property, but that's just a guideline.)

Here's another approach, for earlier versions of C# that do not support automatic properties, and without the underscore in the public property name:

public class LoginDialog 
{
    private static string _user;

    // class members
    public  void RunDialog() 
    {
        _user = "Peter";
    }

    public static string User { get { return _user; } } 
}

Upvotes: 11

Related Questions