Avoiding multiple "if" statements when iterating a list of objects c#

I have various classes which generate excel graphs.

Each class generates a different graph.

They all share the same private variables, with different values.

I wish to write a generic code, in order to prevent "if" statements to determine which graph is it.

Here is an example of one of the classes:

using System;

namespace GraphsGenerator
{
   public class GraphOne
   {
       #region Private Members

       private string m_baseDir = "";
       private static string m_graphName = "GraphOne";
       private string m_imageFile = m_graphName + Utils.ImageExtension;

       #endregion Private Members

       #region Properties

       public string BaseDir
       {
           set { m_baseDir = value; }
       }
       public string GraphName
       {
           get { return m_graphName; }
       }
       public string ImageFile
       {
           get { return m_imageFile; }
           set { m_imageFile = value; }
       }

       #endregion Properties

       #region Constructor


       public HandTrackingGraphs(string baseDir)
       {
           m_baseDir = baseDir;
       }

       #endregion Constructor
   }
 }

I tried to do this in my main:

List<object> listOfGraphs = new List<object>();
listOfGraphs.Add(new GraphOne());
listOfGraphs.Add(new GraphTwo());
listOfGraphs.Add(new GraphThree());

foreach (object currentGraph in listOfGraphs)
{
   string imageFile = currentGraph.ImageFile;
}

But of course this cannot be done.

Any ideas?

Jon Skeet
people
quotationmark

They all share the same private variables, with different values.

They should all implement the same interface, which exposes the ImageFile property. For example:

public interface IGraph
{
    // TODO: Consider making this read-only in the interface...
    public string ImageFile { get; set; }
}

Then you can have:

List<IGraph> listOfGraphs = new List<IGraph>();
listOfGraphs.Add(new GraphOne());
listOfGraphs.Add(new GraphTwo());
listOfGraphs.Add(new GraphThree());

foreach (IGraph currentGraph in listOfGraphs)
{
   string imageFile = currentGraph.ImageFile;
}

You could use an abstract base class instead of an interface, too. That's a bit more restrictive, but it means graphs could share common implementation too.

(You could even create an interface implemented by an abstract base class, if you really wanted the flexibility but also code reuse.)

people

See more on this question at Stackoverflow