user96377
user96377

Reputation:

Calling a Variable from another Class

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.

Upvotes: 20

Views: 267172

Answers (3)

Francis B.
Francis B.

Reputation: 7208

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

Upvotes: 18

ChaosPandion
ChaosPandion

Reputation: 78252

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

Upvotes: 3

Nathan W
Nathan W

Reputation: 55472

That would just be:

 Console.WriteLine(Variables.name);

and it needs to be public also:

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

Upvotes: 49

Related Questions