views:

1714

answers:

4

How can I call a variable from a public class to another public class in C#. I have:

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

I need to call it from:

public class Main
{
}

Thanks for help in advance.

Working in a Console App.

+5  A: 

That would just be:

 Console.WriteLine(Variables.name);

and it needs to be public also:

public class Variables
{
   public static string name = "";
}
Nathan W
I've tried that, and I get:Variables.name is inaccessible due to its protection level
S3THST4
are you sure you added the public modifier.
Nathan W
When I responded, for some reason I didn't see the public modifier you added. Yes, it worked. Thanks a bunch :)
S3THST4
+1  A: 

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
ChaosPandion
+2  A: 

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;
    }
}
Francis B.
Actually, it would be better for him to not have variables within a static class.
ChaosPandion
why do you say that...why not?
Nathan W
It may just be me, but I think it is good practice to make static classes completely stateless.
ChaosPandion
I see, well I do agree on that point.
Nathan W
@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.
Francis B.
why not use (public const String name = "MyName";) ?
ChaosPandion
A: 

Hi! I think there could be two issues. One make sure the name member variable is public as pointed out previously and two Gurus can correct me if I am wrong, static members variables can only be accessed by static member method. So you have to call the name static member variable from a static method. Here is the code that works.

public class Variable
{
    public static string name = "Gautam";
}
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Variable.name);
    }
}
kobra
nope static methods, fields and properties can be accessed by instance members.
Nathan W
Sorry, my mistake, its the other way round. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.
kobra
Exactly, that's because they are static and no nothing about the instance of the object.
Nathan W