apache / apache/lucenenet

Remove unnecessary casting from Clone() methods

Open
#430 7 comments 0 reactions 1 assignee Claimed by @NightOwl888 View on GitHub
design performance pri:normal
Dominant language
C#
Stars
2.4k
Forks
658
Avg merge
3d 5h
Merged PRs (30d)
9

Description

In 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.

```c#
public virtual object Clone()
{
return (MergeScheduler)base.MemberwiseClone();
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.