Shreeraj Bhat
Shreeraj Bhat

Reputation: 231

How to return different class object depending on some condition?

I have method where I create class object depending on some condition and want to return only that object which satisfies the condition. In the return method I need to call that object's class method

I can do with object, dynamic, or Tuple but how can we do with reflection or some other method to return only one object?

public dynamic GetInvokeType(string id)
{
    log.Info("GetInvokeType(): " + id);

    if (id.ToLower() == "cm")
    {
        BCMSDashboardManager b = new BCMSDashboardManager();
        return b;

    }
    else
    {
        SIPManager s = new SIPManager();                
        return s;

    }
}

In the returned method, I will be calling its method based on the returned class object. So, I want to return only one object, not in Tuple, object, or dynamic type.

Upvotes: 2

Views: 4499

Answers (1)

Aleksej Vasinov
Aleksej Vasinov

Reputation: 2797

You should read a bit about factory pattern.

Shortly, you should do smth like this:

  • Create common interface IManager for you manager (SIPManager, ...)
  • some method which will return instance of class (which implements IManager interface)

    // Common interface with desired methods
    public interface IManager
    {
        void Manage();
    }
    public class BCMSDashboardManager : IManager
    {
        public void Manage()
        {
            Console.WriteLine("BCMSDashboardManager");
        }
    }
    public class SIPManager : IManager
    {
        public void Manage()
        {
            Console.WriteLine("SIPManager");
        }
    }
    

And now you could create factory method, which returns instances of specific class

public IManager GetInvokeType(string id)
{
    switch (id.ToUpperInvariant())
    {
        case "CM":
            return new BCMSDashboardManager();
        default:
            return new SIPManager();
    }
}

Upvotes: 4

Related Questions