Alias Extensions (Proposal) #7863
Unanswered
TimberStalker
asked this question in
Language Ideas
Replies: 1 comment 1 reply
-
You should look into implicit/explicit extensions (formerly Roles & Extensions) #5497 |
Beta Was this translation helpful? Give feedback.
1 reply
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.
-
Alias Extensions
Summary
The idea behind alias extensions is to provide the ability to add methods/properties/interfaces to preexisting types without modifying them directly. This would be useful in adding interfaces to types they are not accessible to the developer.
Other similar proposals exist, however this prioritizes reusing existing keywords and keeping syntax similar to constructs already in c#.
Motivation
It is difficult to add interfaces and methods to predefined datatypes that the developer doesn't have access to.
Detailed design
The way to define an alias extension is as follows:
At this point, the Currency alias functions very similar to a normal type alias. However, some differences apply.
Currency price = 1;
would produce a syntax error whileCurrency price = (Currency)1;
would not.The reason why the int must be cast directly to the Currency type alias is because alias extensions are implicitly preceded with an
explicit
modifier. In order for a type to be implicitly assigned to its alias(and vise versa) is to prefix the using declaration with theimplicit
modifier. (Note: Two aliases aliasing the same type must always be cast to the other alias upon assignment, irrespective of theexplicit
/implicit
modifiers defined on them.)Adding extensions methods, properties, or interfaces (aliases may also be assigned their own attributes) can be done as follows:
Currency
type alias implementsIFoo
, and has theCents
andDollars
properties accessible. In order to use it, any int simply needs to be cast to theCurrency
alias, and all defined items can be used.An alias extension may define a constructor, however, the constructor must be parameterless, and only executes upon a type being casted to the alias. As such, all values of the original type have already been set. For more complex actions upon casting, it is expected for one to create a static method on the alias that accepts the original type and returns the alias.
Drawbacks
Complexity is added to the code, and random functions that were not originally on types may start appearing.
Additionally, as methods, interfaces ect are not added to the original type, code may be littered with aliases.
Alternatives
What other designs have been considered? What is the impact of not doing this?
Unresolved questions
Design meetings
Link to design notes that affect this proposal, and describe in one sentence for each what changes they led to.
Beta Was this translation helpful? Give feedback.
All reactions