-2
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.

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
Iam The6
  • 11
  • 2
  • 1
    those aren't declared globally. – Daniel A. White Apr 10 '17 at 00:55
  • @OusmaneMahyDiaw what do you mean? the SomeOther is a class? basically SomeOther is a timer elapsed method and I don't want to set a new question every second of the tick. I hope you understand what I mean.. – Iam The6 Apr 10 '17 at 00:58
  • @IamThe6 Currently the "SomeOther" method is not inside a class, that's what I mean. nevertheless, you'll need to declare the "questionToAsk" globally. – Ousmane D. Apr 10 '17 at 01:00
  • @OusmaneMahyDiaw okay how do i make it global? I tried using static class but got error. please see edits// – Iam The6 Apr 10 '17 at 01:05
  • you can't use a var as a public static. it needs to be declared by type. http://stackoverflow.com/questions/14572690/is-it-possible-to-have-a-var-as-a-global-variable/14572722 – ferday Apr 10 '17 at 01:09

1 Answers1

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.

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88