The most clear case of the problem is function Clone (just an EXAMPLE guys). Let's say you have BaseClass and DerivedClass -- unless I miss something, in both functions (Clone per each of the class) you create BaseClass and DerivedClass respectively but you return object actually. This is the problem if you want to work with "real" class.
So far I see only two workarounds to this problem:
1. each time cast the result of the function to appropriate class
var real_stuff = (RealStuff)x.Clone(); // I want real stuff
2. provide second function, so you would have Clone (if you work at base class level) and CloneThis (which result would change from class to class, if you want to work at given class level)
public override object Clone()
{
return CloneThis();
}
public RealStuff CloneThis()
{
return new RealStuff(this);
}
The first one is ugly, the second one is tiresome.
QUESTION: how do you deal with this issue?
Another thing -- please comment on this as well if you like -- is why when overriding the function signature checking is so strict? Besides "because it was designed that way" or Eric Lippert's favourite "because every feature requires..." ;-) I see no technical (and logical, and so on) problems with allowing to override a function with changed result type IF the overriden function result is derived from original function result type.
Example:
class ClassA
{
public virtual ClassA GetIt() ...
}
class ClassB : ClassA
{
public override ClassB GetIt() ...
}
Currently it is not correct code, but I think it technically could be, because ClassB is derived from ClassA. And whatever you do with the output, the "receiver" expects ClassA, so ClassB fullfils this requirement.
So you could write:
ClassA class_a_b = new ClassB();
ClassB class_b_b = new ClassB();
ClassA result1 = class_b_b.GetIt();
ClassA result2 = class_a_b.GetIt();
ClassB result3 = class_b_b.GetIt();
// incorrect, derived GetIt would be called OK,
// but the signature is taken from ClassA
ClassB result4 = class_a_b.GetIt();
I also don't think with such capabilities anyone would be surprised by the behaviour, IMHO it is consistent.
Please keep your answers on-topic, "You shouldn't use ICloneable" is NOT on topic. Thank you.