-1

So I have a static class with a list declared as one of it's members, and I populate the list in a function lets say it's called PopulateList(). Is it possible to modify the list in another function without:

1) Calling it as a parameter 2) Instantiating it in a constructer (Trying to keep the class static. I'm working off of a template so I can't really change the structure of the classes)

Without somehow instantiating though, I will obviously receive null exceptions, so I was wondering if there is a 3rd way to do this.

       public Static class MyClass{

             static public List<String> m_SuiteFileNameList2=null;


        public static bool Function1(inp){
              //m_SuiteFileNameList2 stuff
         }

        public static void Function2(){
             //m_SuiteFileNameList2 other stuff
          }
       }
user1819301
  • 113
  • 4
  • 17

2 Answers2

2

You can either use a static constructor, or static initialization. It will allow you to keep your class static, but will ensure that the list is always defined:

static class MyClass
{
    static MyClass()
    {
        MyList = new List<Whatever>();
    }

    // etc
}

or

static class MyClass
{
    public static List<Whatever> MyList = new List<Whatever>();
}

Another option is to add a null check to every usage of the list:

public static void MyMethod()
{
    if (MyList == null)
    {
        MyList = new List<Whatever>();
    }
    //etc
}
RoadieRich
  • 6,330
  • 3
  • 35
  • 52
1

I would call a function called 'Initialize' which is static and takes care of your static members.

Though I would recommend against static members if possible.

Why?

code snippet

public static class YourClass
{
    public static List<string> YourList;

    public static void InitializeList()
    {
        YourList = new List<string>();
        YourList.Add("hello");
        YourList.Add("how");
        YourList.Add("are");
        YourList.Add("you?");
    }
}

Call your Initialize-Function from outside:

 YourClass.InitializeList();

EDIT: Given your code , you can also do it this way:

  public Static class MyClass{

             static public List<String> m_SuiteFileNameList2=null;


        public static bool Function1(inp){
             if(m_SuiteFileNameList2 == null)
             { m_SuiteFileNameList2 = new List<String>();}
              //m_SuiteFileNameList2 stuff
         }

        public static void Function2(){
             if(m_SuiteFileNameList2 == null)
             { m_SuiteFileNameList2 = new List<String>();}
             //m_SuiteFileNameList2 other stuff
          }
       }
Community
  • 1
  • 1
Fabian Bigler
  • 10,403
  • 6
  • 47
  • 70
  • I disagree with point 2 `They use memory even though you don't use the class (they live as long the project lives)` This is false unless you Use it atleast `Once` – Sriram Sakthivel Jul 16 '13 at 16:04