Wednesday, April 13, 2011

C# Design question - Static var?

I have the following class hierarchy

public abstract BaseClass : System.Web.UI.UserControl
{

  public virtual void Process(string sType)
  {
     //Do something
     //Here I want to create a CSV list Ex: "type1, type2"
     //Do I need to create a static variable? There might be several controls calling //Process. I need to scope it to the UserControl
  }
}

In a user control that inherits from BaseClass

public void ProcessParams()
{
  base.Process("type1");
  base.Process("type2");
}
From stackoverflow
  • I would avoid doing this in a static, unless you want to store params from across all instances. You could add a collection to your base class, or have an IEnumerable as the parameter for Process().

  • Further, you could use the Singleton Pattern.

  • I'm not sure what you're specifically trying to accomplish, but I see no reason for any static variables.

  • If you have subclasses based on instances (regardless of whether they're UserControls or not), then you don't want to use static fields. You'll want to use instance fields so your Process() method returns the appropriate values contextually to each individual user control.

    Use static fields if you want the return value of Process() to be the same across all subclass instances of your BaseClass. Hope this helps!

  • To create a single list of all the strings passed to the base class's Process method, you would need a static member.

    public abstract BaseClass : System.Web.UI.UserControl
    {
      private static List<string> collection = new List<string>();
      private static string csvString = String.Empty;
      public virtual void Process(string sType)
      {
         //to create a list
         collection.Add(sType);
         //Or to create just a csv string
         csvString += sType + ",";
      }
    }
    

    It's important to note though, how you currently have the method declared, as a public virtual, may not always be called, if a child class overrides the functionality.

0 comments:

Post a Comment