Home > Net >  C# How to access a List instance created by another class
C# How to access a List instance created by another class

Time:04-22

The answer to this question might be super obvious to anyone, but at the moment I'm having an issue trying to figure out how to access a List made in a previous class.

Here's what I'm doing currently, which causes the error "An object reference is required for the non-static field, method, or property 'TestClass.TestList'".

public partial class TestClass
    {
        // Make a static list
        public static List<string> TestStaticList = new List<string>();
        // Make a non-static list - How do I reference this?
        public List<string> TestList { get; set; }
        
        // Clear the static list, and add the entries of the non-static list
        public static void UpdateList()
        {
            TestStaticList.Clear();
            for (int i = 0; i < TestList.Count; i  )
            {
                string NewString = TestList[i];
                TestStaticList.Add(NewString);
            }
        }
    }

My question is just how can do I reference that List? It's worth noting that I do need it to remain non-static. I've looked around for information regarding this but so far either I've not found any or I didn't notice it to be a solution to my issue, so I'm sorry if this is a duplicate. Thanks in advance for any help.

CodePudding user response:

The reason that you're seeing that error is because you're not able to reference a non-static property in a static method.

Without making TestList static, your best bet would be to pass TestList or TestClass as a parameter into UpdateList. For example:

public static void UpdateList(TestClass testClass)
{
    TestStaticList.Clear();
    for (int i = 0; i < testClass.TestList.Count; i  )
    {
        string NewString = testClass.TestList[i];
        TestStaticList.Add(NewString);
    }
}

CodePudding user response:

As you "need it to remain non-static", then it's impossible for you to access it in a static method, because non-static members(fields, methodd, properties and events alike) are 'linked' to (or associated with) its instance. In other words, those in different instances MAY have different values. In a static method, which isn't associated with any instance, you of course can't ask the compiler to access the non-static member, because it won't know which instance the member is associated with. You can specify the instance by using "A.TestList". If you want the method to access every instance you can maintain a static List and call Add(this) in the constructor and remove itself in the destructor and iterate the list in your method.

  •  Tags:  
  • c#
  • Related