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.
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.
That would just be:
Console.WriteLine(Variables.name);
and it needs to be public also:
public class Variables
{
public static string name = "";
}
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
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;
}
}
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);
}
}