I have the following three classes
public class Base
{
string name;
}
public class Foo : Base
{
int value;
}
public class Bar : Base
{
double value;
}
This is what I’m attempting
Base current = null;
if (somecondition)
current = new Foo();
else
current = new Bar();
for (int i=0; i<5; i++)
{
current.value = i;
}
The problem is VS 2010 shows an error in the loop body because Base doesn’t have a property value.
Now, I could workaround this issue by this way:
Base current = null;
bool isBar = true;
if (somecondition)
{
current = new Foo();
isBar = false;
}
else
current = new Bar();
for (int i=0; i<5; i++)
{
if (isBar)
(current as Bar).value = i;
else
(current as Foo).value = i;
}
But I was hoping for a better solution because once the loop starts iterating, the type of current isn’t going to change, yet I am going to test the type and accordingly cast it for each iteration.
What would be the right way to do this?
After making the fields accessible (or exposing them as accessible properties instead), your options are:
dynamicif you’re using C# 4 – just declarecurrentasdynamic, and you can assign tocurrent.valueand the compiler will insert code to work it out at execution timePersonally I would at least consider the last approach – is inheritance definitely appropriate here? Do the two types for
valuereally need to be different? Do they have the same meaning, and if so would it make sense to push the value to the base class and potentially make it generic if you need different types?