views:

57

answers:

1

Here is what I am trying to do:

if (a==true) 
{
    dbA objectInstance = new dbA();
}
else
{
    dbB objectInstance = new dbB();
}

objectInstance.Name = "New name";

I get "the name objectInstance does not exist in the current context", I assume because the def happens inside the conditional.

There must be a better pattern to do this - should I have dbA and dbB inherit from the same class?

+4  A: 

Yes, dbA and dbB would need a common base class or interface and that base class or interface would need to have the Name property as part of its public contract.

Then you could do this:

SomeBase objectInstance;

if (a==true) 
{
    objectInstance = new dbA();
}
else
{
    objectInstance = new dbB();
}

objectInstance.Name = "New name";

That being said I think an interface is your best choice here unless these types already share a base class.

Andrew Hare
No need to assign to null to start with - indeed, I *wouldn't* to make it clear it'll definitely be assigned in one of the conditions.
Jon Skeet
You are right! I wasn't near a compiler so I couldn't remember if the compiler would complain about the unassigned variable. :)
Andrew Hare