I'm considering to use new
to redefine members in subclasses to make more specific return type available. The question is: is this a good idea, or is it asking for troubles?
The problem to be solves is when there are several "mirrored" class hierarchies, where types from every hierarical layer are referencing to the same level of another hierarchy. It's hard to explain, so here is an example:
class A1 {}
class A2 : A1 {}
class A3 : A2 {}
abstract class B1
{
protected A1 myA;
A1 MyA { get { return myA; } }
}
abstract class B2 : B1
{
new A2 MyA { get { return (A2)myA; } }
}
class B3 : B2
{
new A3 MyA
{
get { return (A3)myA; }
set { myA = value; }
}
}
There is code which only handles the abstract "level" 1 (A1
/ B1
etc), just as well for every other level. It would be nice when each "level" would see the types as specific as possible. Currently, I defined the types on the top most level and downcast it all the time in the calling code. Sometimes I add another member for some "level" using another name, this results in many more redundant members. I want to make it cleaner.
(Generics are not an option here, because B2
wouldn't be useful without knowing B3
(it would need additional interfaces there). And if there are many types (eg. also C1/2/3, D1/2/3 ...) there would be too many generic arguments. Technically it would work, but it just gets very complicated.)
Additionally I will serialize some of these classes (DataContractSerializer
) and some will be mapped to a database using NHibernate.
Did anyone already do something like this? Is it recommendable? Are there any other approaches to solve the same kind of problem?
Edit: I changed the code a bit because of the discussion about the casts and the implementation of the properties. This is actually not the question here. I just tried to write as little code as possible to make a short example.