user258959
user258959

Reputation: 93

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
}

Upvotes: 0

Views: 557

Answers (3)

Housheng-MSFT
Housheng-MSFT

Reputation: 772

Instantiate a collection with generics in a class. If the collection has no elements, you can initialize the properties through the constructor in a method, and add the initialization object to the collection object.

public class Program
{

    List<Questions> qList = new List<Questions>();
    public void Test()
    {
        qList.Add(new Questions("1", "2", "3", "4", "5"));
    }

}

Upvotes: 1

Nitin S
Nitin S

Reputation: 7601

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
    }
}

Upvotes: 1

Jamiec
Jamiec

Reputation: 136164

This is not valid code

public class GeneQuestions {

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

You can only initialize fields/properties inside the body of a class all other code needs to go into constructor(s)/method(s) or propert(y/ies)

public class GeneQuestions {

  private List<Questions> qList = new List<Questions>()
  {
    new Questions("q1","a1","a2","a3","a4") // this is fine, initializing the List
  }

  public GeneQuestions() // ctor
  {
      qList.Clear(); // a method call needs to be inside a method (ctor in this case)
  }
}

Upvotes: 1

Related Questions