20

How can I access a variable in one public class from another public class in C#?

I have:

public class Variables
{
   static string name = "";
}

I need to call it from:

public class Main
{
}

I am working in a Console App.

3 Answers 3

49

That would just be:

 Console.WriteLine(Variables.name);

and it needs to be public also:

public class Variables
{
   public static string name = "";
}
Sign up to request clarification or add additional context in comments.

4 Comments

I've tried that, and I get: Variables.name is inaccessible due to its protection level
are you sure you added the public modifier.
When I responded, for some reason I didn't see the public modifier you added. Yes, it worked. Thanks a bunch :)
I get an object reference is required for non-static field.
18

I would suggest to use a variable instead of a public field:

public class Variables
{
   private static string name = "";

   public static string Name
   { 
        get { return name; }
        set { name = value; }

   }
}

From another class, you call your variable like this:

public class Main
{
    public void DoSomething()
    {
         string var = Variables.Name;
    }
}

5 Comments

Actually, it would be better for him to not have variables within a static class.
why do you say that...why not?
It may just be me, but I think it is good practice to make static classes completely stateless.
@Chaos: Well, I could agree with you. But in this case, the variable name seems to be a constant and it seems to me more elegant to use a static variable.
why not use (public const String name = "MyName";) ?
3

You need to specify an access modifier for your variable. In this case you want it public.

public class Variables
{
    public static string name = "";
}

After this you can use the variable like this.

Variables.name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.