and no... that defeats the purpose of what im trying
todo..
encapsulate all initializing of variables in base
class...
derive from it... by deriving from base class, and
casting, derived classes would already have their
variables initialiezed(cause they have already been
initialized in the base class) ....
abstract class II_interface
{
private m_var;
public int varVar
{
get
{ return m_var; }
set
{ m_var = value; }
}
}
class myDerived : II_derived
{
public myDerived(int val)
{ base.varVar = val }
public int varVarVar
{
get { return base.varVar; }
}
}
class myDerived2 : II_derived
{
public int varVarVar
{
get { return base.varVar; }
}
}
class test
{
int function
{
II_interface c1 = new myDerived(6);
II_interface c2 = (myDerived2)c1;
// this would print "6" if this function were called
Console.WriteLine("{0}",c2.varVarVar.ToString());
}
}
Notice how im initializing in the first class... and
gather the values int he second class, without using the
constructor on the second class.. im simply casting.
This way im doing the work in the first class,
initializing variables, calling the contructor, etc.
Then by casting, all the work is done for me.. and the
second class can use the vars in first class that are
already initialized.
Thanks
-----Original Message-----
public class Test
{
myDerivedClass c1 = new myDerivedClass();my question is why am i getting the invalid cast
exception.
You can't because althought myDerivedClass and
myDerivedClass2 implementsthe same interface, they are not the same with each other. myDerivedClass2is *not* myDerivedClass. myDerivedClass2 is II_interface.
Why do you want to cast on the list into different types?
Can't you juststore the correct object in the list? For example:
IInterface[] array = new IInterface[] {new myDerivedClass1
(), newmyDerivedClass2(), new myDerivedClass3()};
You can also substitute IInterface with a BaseClass.
HTH,
/m
If this is not possible, how can i make it
possible.
What i'm trying to do, is
1) make one class with properties.
2) derive several other class from the first class, each class having it's own set of properties (and since im
deriving, all the properties from the first class)
3) create an array of the first class
4) for each element in array, based on a unigue type or
enum, cast the element to the correct derived class.
This kinka like a factory pattern, but i didn't want to
implement the factory.. i just want to be able to cast,
so I can set up the first classes' properties, then use
the derived classes to access the already setup variables in the first class. the first class will be the only
class with a public contructor. The rest of the derived classes will be casted, to use the base classes already
created/filled properties.
Thanks
Kurt Lange
.
..