Kokombads
Kokombads

Reputation: 460

What type should I declare to my object to make it accept different constructors from different classes

I need to declare a global variable (it is that variable that you declare on top of a certain class right?) but the problem is, C# prohibits me to declare it as "var" type. so I've got a trouble making it dynamically accept different kinds and types of constructors. I'm using C# & WPF.

var itemObject; //error, I can't declare it as var

    public void LoadGridview(string Moder)
    {
        if (Moder == "Persons")
        {
            itemObject = PersonsMgr();
        }`enter code here`
        else if (Moder == "Car")
        {
            itemObject = CarsMgr();
        }

    }

Upvotes: 1

Views: 55

Answers (3)

Nitin Joshi
Nitin Joshi

Reputation: 1668

S McCrohan is correct, if you have something common in both classes then you should have created a base class or interface containing those common members. But due to any reason if you haven't implemented any base class or interface then there is another solution if you are using .Net Framework 4.0 or greater:

dynamic itemObject; //Now you can declare the variable which will accept any constructor
public void LoadGridview(string Moder)
{
    if (Moder == "Persons")
    {
        itemObject = PersonsMgr();
    }
    else if (Moder == "Car")
    {
        itemObject = CarsMgr();
    }
}

The only problem with this approach is that intellisence won't display the list of properties or methods after placing a dot after object name. You will have to explicitly write the name of any property or method you want to use. It won't give any compile time error but if that property or method won't be resolved at runtime it will throw an error.

Upvotes: 1

S McCrohan
S McCrohan

Reputation: 6693

Trying to do this only makes sense if the PersonsMgr and CarsMgr classes have some members or methods in common, which you're expecting to access later. Create a parent class for them both to extend, or an interface for them both to implement, and declare itemObject using that.

Upvotes: 0

TGH
TGH

Reputation: 39248

I would look into C# generics. It's a way to use make your objects flexible when it comes to types.

http://msdn.microsoft.com/en-us/library/512aeb7t.aspx

Upvotes: 0

Related Questions