Remove unnecessary casting from Clone() methods
See original GitHub issueIn Java, overridden methods in subclasses can return a different type than the base class. Therefore, it is common in Java to declare the clone()
method with the subclass type so there is no need for the consumer to cast the return value of the method.
In .NET, this only works if a class is sealed, since it would otherwise constrain the subclass to that of the base class type. While we don’t use the ICloneable
interface in .NET per Microsoft’s recommendation, we left the return type as object
for compatibility and provide an option for 3rd parties to create a custom compile that implements ICloneable
in all of the appropriate places. While this affects usability somewhat by requiring a cast, the fact of the matter is object
return type is the only thing we can do consistently across the API even if we took out the ICloneable
option.
Although the return type of Clone()
is always object, many of the original casts to a specific type were carried over from Java and they can now be removed. In particular, there are some calls to MemberwiseClone()
that are cast to a more specific type even though the return type is object
and there is no need to set any of its members.
public virtual object Clone()
{
return (MergeScheduler)base.MemberwiseClone();
}
Issue Analytics
- State:
- Created 3 years ago
- Comments:6 (5 by maintainers)
Great. Without further ado we will remove the
ICloneable
feature (which was only a non-default option).However, unfortunately covariant returns are only supported on .NET 5+ target frameworks. I have done a test locally to confirm this is the case.
That said, I am on board with getting rid of casting (by end users) on the
Clone()
methods in every case where we can at the expense of API consistency.Again, this will probably not break anyone’s code, they will just no longer have to cast in some cases. Projects that are upgraded from prior targets of .NET to .NET 5+ will have no casting to do at all with
Clone()
methods.All other methods we will have consider on a case by case basis whether supporting covariant returns is worth the cost of maintaining diverging code and diverging APIs, since this feature is only supported on .NET 5 targets.
@NightOwl888 I think that approach makes good sense. I’m totally onboard with that. That let’s the project leverage covariant returns when targeting .Net 5 and gives other targets the best experience they can have. Perfect.