[Proposal] Auto-Constructed Propoerties #2768
Unanswered
VBAndCs
asked this question in
Language Ideas
Replies: 4 comments
-
Look at Primary Constructors #2691 |
Beta Was this translation helpful? Give feedback.
0 replies
-
@Joe4evr
Example:
This will generate: class MyClass
{
private int X {get; set;}
public int Y {get;}
protected int Z {get; set;}
public MyClass(int x, int y, int z)
{
X = x;
Y = y;
Z = z;
}
public MyClass(string Msg)
{
X = 0;
Y = 1;
Z = 2;
//do something
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
Are you trying to make Also #2721 |
Beta Was this translation helpful? Give feedback.
0 replies
-
@Thaina |
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.
-
I suggest to use a Constructed attribute to auto initialize some properties and fields through the constructor. This will save a lot of coding in cases where there is no need to process the constructor params..
This will be helpful in many cases, such as dependency injection through constructors used a lot in controllers and PageModels in ASP.NET Core.
Example:
Roslyn can generate this code:
If we want a constructor that doesn't initialize the properties:
Note that using attributes doesn't need to make any changes in the compiler. It can be done by Roslyn to lower the code directly.
But @bandleader suggested two other alternatives to this syntax based on type script:
or:
Which are more compact, but need to override the properties if we need to use write the get and set blocks.
The first syntax needs to define the properties repeatedly in all constructors. The second one overcomes that disadvantage, and if we use the [NonConstructing] attribute with some constructors, we will have the ability to define regular constructors as well.
So, the last syntax seems flexible and is also compact unless we have to override some properties to have a full body, where using the [Constructed] will be better.
In this case, I think we can have a mix of the first syntax and the third syntax to get the best of them.
Beta Was this translation helpful? Give feedback.
All reactions