where
scope inside generic class body to define methods/properties only relevant for certain types
#8206
Unanswered
thomhurst
asked this question in
Language Ideas
Replies: 3 comments 3 replies
-
Beta Was this translation helpful? Give feedback.
0 replies
-
You can use extension methods to achieve that : public static class Ext
{
public T GetMedianNumber<T>(this MyList<T> list)
where T : INumber<T>
{ ... }
public bool IsInAlphabeticalOrder<T>(this MyList<string> list)
{ ... }
} Personally, I would like having |
Beta Was this translation helpful? Give feedback.
3 replies
-
Generic types in .NET can't conditionally have different members based on the generic type argument. However, the concept of |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Currently, if we declare a generic type without a hierarchy constraint, such as a
MyList<T>
, it can hold anything.But what if we wanted to create a method only when
T
is a certain type?We can't declare two
MyList<T>
with different constraints, as that'll create a type conflict.Currently, we have to use extensions methods for this.
What about a
where
scoped block where we can define instance level methods/properties that are only accessible when that generic constraint is met?And example usage:
Beta Was this translation helpful? Give feedback.
All reactions