Search code examples
c#visual-studiounity-game-enginecustom-lists

Why can't I use a custom List outside the main method in C#?


I'm trying to write a custom class and create a List instance of that class in another class. However, Visual Studio doesn't recognize my custom list. I have a class Questions and another class GenQuestions. Below are my codes. I just want to be able to create an instance of the Questions class outside of main method, in this case in GenQuestion class below. I'm using Unity, by the way.

Questions class

using System;
using System.Collections.Generic;
using UnityEngine;

public class Questions 
{
    
    public string question { get; set; }
    public string optionA { get; set; }
    public string optionB { get; set; }
    public string optionC { get; set; }
    public string optionD { get; set; }
    public Questions(string q, string a, string b, string c, string d) {
        question = q;
        optionA = a;
        optionB = b;
        optionC = c;
        optionD = d;
    }
}

and here is the GenQuestion class. Not sure what I'm doing wrong here (below) that Visual Studio doesn't recognize my qList after inistantiating it.

using System;
using System.Collections.Generic;

public class GeneQuestions {

    List<Questions> qList = new List<Questions>();
    qList.   // Visual Studio doesn't recognize this list variable
}

Solution

  • You cannot use a variable directly inside a class after declaration. A class is not like main method.

    You need to write your code inside a method in a class after declaring the class level variable

    public class GeneQuestions 
    {
    
        List<Questions> qList = new List<Questions>();
        public voids Test()
        {
            qList.   // Do something
        }
    }