Yes but you're using a common type to hold the specific types so you can only deal with one variable.
Here's a quick and dirty example, I'm going to use public members to cut down on typing, you probably shouldn't code like this ;)
Declare some types...
- class BaseType
-
{
-
}
-
-
class DataType1 : BaseType
-
{
-
public int Age;
-
}
-
-
class DataType2 : BaseType
-
{
-
public string Name;
-
}
Now decide what's kind of data we're going to set up.
-
BaseType myItem = null;
-
int flag = 0; // or whatever you want
-
switch (flag)
-
{
-
case 0:
-
{
-
DataType1 newItem = new DataType1();
-
newItem.Age = 27;
-
myItem = newItem;
-
break;
-
}
-
case 1:
-
{
-
DataType2 newItem = new DataType2();
-
newItem.Name = "GaryTexmo";
-
myItem = newItem;
-
break;
-
}
-
}
myItem is going to contain the data you want, but it won't be accessible because myItem is of type BaseType, which has absolutely nothing in it. If I want to access the data, I can do the following...
- if (myItem != null)
-
{
-
if (myItem is DataType1)
-
{
-
Console.WriteLine("Item is DataType1...");
-
Console.WriteLine(" Age is " + ((DataType1)myItem).Age);
-
}
-
else if (myItem is DataType2)
-
{
-
Console.WriteLine("Item is DataType2...");
-
Console.WriteLine(" Name is " + ((DataType2)myItem).Name);
-
}
-
else
-
{
-
Console.WriteLine("Unrecognized type...");
-
}
-
}
So while inheritance gives you the generalized type to pass around your program, you can always get back to the more specific type. This is what you said you wanted to do in your first post.
Your alternative would be to create a whole bunch of member variables for each type and assign them to null, only ever accessing the one for the type you want. This will work, but it's a lot of overhead and wasted code.
Does that help any?