Constructed type reference #2839
Replies: 3 comments
-
Your suggestion is also closely related to Shapes #164 which I think will give you what you want. I agree that this is something that's sorely missing from C#, but it's due to a limitation of the CLR that will hopefully be lifted if covariant return types are implemented. In my opinion, it's a massive hack that in C# the only way to actually write an public interface IEquatable<T>
{
bool Equals(T other);
} This works, but it's a hack because the implementor can pass any type it likes for the C# does nothing to prevent you from writing the following jibberish: public class Foo : IEquatable<DateTime>
{
...
} Shapes should hopefully bring some of the features of typeclasses to C#, such as being able to use Maybe one day: shape SAnimal : new()
{
public this[] Parents { get; private set; }
public this Breed(this other) => new this
{
Parents = { this, other }
};
} We can but dream. |
Beta Was this translation helpful? Give feedback.
-
IIRC covariant return types wouldn't require any CLR changes, although it might be cleaner with CLR changes. Without CLR changes it would require a bridge method which overrides the base method and calls the method with the covariant return. This is how Java does it. |
Beta Was this translation helpful? Give feedback.
-
@Richiban |
Beta Was this translation helpful? Give feedback.
-
Disclaimers
Feel free to suggest a better name for this feature.
This feature was first suggested at #49 (comment), as it overlaps with "Covariant Return Types", but they are now split since there are use cases only covariant return types can achieve and use cases only constructed type reference can achieve.
As stated by @HaloFour at #49 (comment), this proposed feature probably requires CLR changes (#317).
Introduction
CRTP allow developers to achieve some next level generic code, but it comes at a price, like the following:
Proposal
What if C# had this
T
type for the constructed type out of the box, without the need for an actual generic enclosing type? Like this:Open questions
TConstructed
is just a placeholder here. How should it be called? Also, a currently non-reserved keyword would be a breaking change for classes that already have a defined member with the same identifier, unless any identifier hid the one this feature designs (just like what I think it happens for discard operators).typeof(this)
. Besides ugly, it seems inconsistent, becausetypeof
is meant to return a runtime (and not compile time)Type
reference. But it would fix the breaking change scenario.new()
constraint is defined and used, but in the proposal the constructed type does not necessarily match it. At first, this constraint wouldn't be possible for this feature, but that would make it lack some usefulness.Beta Was this translation helpful? Give feedback.
All reactions