Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics: How to check the exact type of T, without object for T

Tags:

c#

generics

How can i check/evaluate the exact type of T without an object for T. I know my question maybe confusing but consider this...

 public abstract class Business
    {
        public abstract string GetBusinessName();
    }

    public class Casino : Business  
    {
        public override string GetBusinessName()
        {
            return "Casino Corp";
        }
    }

    public class DrugStore : Business 
    {
        public override string GetBusinessName()
        {
            return "DrugStore business";
        }
    }


    public class BusinessManager<T> where T : Business
    {
        private Casino _casino;
        private DrugStore _drugStore;

        public string ShowBusinessName()
        {
            string businessName;
            if (T == Casino) // Error: How can I check the type?
            {
                _casino = new Casino();
                businessName = _casino.GetBusinessName();
            }
            else if (T == DrugStore) // Error: How can I check the type?
            {
                _drugStore = new DrugStore();
                businessName = _drugStore.GetBusinessName();
            }

            return businessName;

        }
    }

I just want to have something like this on the client.

    protected void Page_Load(object sender, EventArgs e)
    {
        var businessManager = new BusinessManager<Casino>();
        Response.Write(businessManager.ShowBusinessName());

        businessManager = new BusinessManager<DrugStore>();
        Response.Write(businessManager.ShowBusinessName());
    }

Notice that I actually didnt create the actual object for Casino and Drugstore when I call the BusinessManager, I just pass it as generic type constraint of the class. I just need to know exactly what Type i am passing BusinessManager to know what exactly the Type to instantiate. Thanks...

PS: I don't want to create separate specific BusinessManager for Casino and Drugstore..

You can also comment about the design.. thanks..

ADDITIONAL: and what if class Casino and DrugStore is an ABSTRACT CLASS =)

like image 270
CSharpNoob Avatar asked Oct 31 '10 17:10

CSharpNoob


1 Answers

You can write

if(typeof(T) == typeof(Casino))

but really this type of logic is a code smell.

Here's one way around this:

public class BusinessManager<T> where T : Business, new() {
    private readonly T business;
    public BusinessManager() {
        business = new T();
    }
}

but personally I'd prefer

public class BusinessManager<T> where T : Business {
    private readonly T business;
    public BusinessManager(T business) {
        this.business = business;
    }

    public string GetBusinessName() { 
        return this.business.GetBusinessName();
    }
}
like image 191
jason Avatar answered Oct 25 '22 01:10

jason