On Tue, 09 Sep 2008 09:58:26 -0700, DaveL <dv*****@sbcglobal.netwrote:
if u notice in my example the class that created the 2
Classes Class1 and class2 ,has no idea of which is which
First: as long as the variable "condition" doesn't change (and in the
design you've presented, it shouldn't), the MainClass class can just check
that variable and cast the instance as needed when it needs access to that
field:
if (condition == 1)
{
int value = ((Class2)ojob).NewField;
}
Second: if for some reason you can't rely on the "condition" variable,
then the previous reply to your question will work fine, just as it was
given. Repeating the example:
Class2 class2 = ojob as Class2;
if (class2 != null)
{
int value = class2.NewField;
}
And alternative to the "as" operator would be to use the "is" operator:
if (ojob is Class2)
{
int value = ((Class2)ojob).NewField;
}
Finally: the other thing that the previous reply was exactly correct about
is that the design you've presented really doesn't look all that sound in
the first place. We can't say for sure, because the code is obviously
just demonstration code, and we have no idea what the larger picture is.
But conditionally processing an instance based on its type is often better
handled in some other way (polymorphism being the most common superior
alternative).
Pete