How to use variables set globally in a method C#

时间:2017-04-10 00:48:48

标签: c# variables

public partial class Form1 : Form
{

}

static class Questions
{
    public static var contents = File.ReadAllLines(@"TextFile/Questions.txt");
    public static var newRandom = new Random();
    public static var randomLine = newRandom.Next(0, contents.Length - 1);
    public static var questionToAsk = contents[randomLine];
}

But it dives me the following error:

the contexual keyword 'var' ....

The variable questionToAsk has a random line from a textfile and it gets set. But when I try to access it from the SomeOther method. I can not call it.

What is a way around this?

Thanks guys.

1 个答案:

答案 0 :(得分:1)

The issue is var you cannot use them to define fields and properties, you can use them to define implicitly typed local variables. you should change the class definition like this:

static class Questions
{
    public static string[] contents = System.IO.File.ReadAllLines(@"TextFile/Questions.txt");
    public static Random newRandom = new Random();
    public static string questionToAsk = String.Empty // Will set it later
}

So you can access those variables by using the class name, Questions like the following:

public partial class Form1 : Form
{
    int randomLine = Questions.newRandom.Next(0, contents.Length - 1);
    Questions.questionToAsk = Questions.contents[randomLine]; 
}

So you have three static variables under the class Questions you can access those variables anywhere in the application by using Questions.variable_name.