I know some codes here are not clear. I’m still in the process of trying out things. I’ve got three questions, why does an error shows up when adding a string in my list? How do I pass the List in Class1 to my main class? And is my syntax correct in List passArr? Not sure if I should add parenthesis at the end of passArr.
class Class1
{
public static List<string> passArr
{
get;
set;
}
public static void passIt()
{
passArr.Add("A"); //Error: Object reference not set to an instance of an object
}
}
Main Class
class Program
{
static void Main(string[] args)
{
Class1.passIt();
List<string> passArr1 = Class1.passArr;
foreach (string s in passArr1)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
}
You’re never creating a list, so the
passArrproperty (which needs renaming, by the way) always has a value ofnull. You need something like:at some point. Another alternative would be to make it a read-only property backed by a field with an initializer:
(This complies with naming convention in terms of case, but it’s still not a meaningful name, of course.)