C# public list of objects

30,422

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>();
Share:
30,422
Matt D. Webb
Author by

Matt D. Webb

I love: Node Chess Coffee

Updated on April 14, 2020

Comments

  • Matt D. Webb
    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
    Matt D. Webb about 10 years
    Thank you! I'm sure you don't need to do this within a class in VB.
  • BRAHIM Kamel
    BRAHIM Kamel about 10 years
    the question is tagged c# not vb.net
  • Darren
    Darren about 10 years
    @K.B - Yes, hence my C# answer. I included the VB.NET snippet to show the OP how to achieve a new instance of an object in C#.
  • Matt D. Webb
    Matt D. Webb about 10 years
    Cheers Darren! Very helpful.