C# public list of objects
Solution 1
You need an instance of your Program
class:
static void Main(string[] args)
{
Program p = new Program(); // p is the instance.
foreach(var player in p.myListOfPlayers)
{
}
}
This is the equivalent of:
Dim p As New Program
Alternatively you could make myListOfPlayers
static.
As an additional comment, you should try and follow proper naming conventions, for example: C#
classes should have their first letter capitalized. players
should be Players
.
Solution 2
By design you cannot access a non static member from a static member
From MSDN
Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.
You need static modifier here
public static List<players> myListOfPlayers = new List<players>();
Comments
-
Matt D. Webb about 4 years
I'm converting from VB to C# and struggling to workout how to access a public list of objects...
class Program { public List<players> myListOfPlayers = new List<players>(); static void Main(string[] args) { foreach(var player in myListOfPlayers) { } } class players { public string playerName { get; set; } public string playerCountry { get; set; } } }
In my Main module I can't access "myListOfPlayers".
-
Matt D. Webb about 10 yearsThank you! I'm sure you don't need to do this within a class in VB.
-
BRAHIM Kamel about 10 yearsthe question is tagged c# not vb.net
-
Darren about 10 years@K.B - Yes, hence my
C#
answer. I included theVB.NET
snippet to show the OP how to achieve a new instance of an object inC#
. -
Matt D. Webb about 10 yearsCheers Darren! Very helpful.