not init property #4202
Unanswered
Terry1511512
asked this question in
Language Ideas
Replies: 2 comments 2 replies
-
The usual response from the LDM when someone wants the language to prevent certain scenarios is to suggest writing an analyzer that implements your specific needs. |
Beta Was this translation helpful? Give feedback.
0 replies
-
Why not use a instance method as "setter" for that? public class Idea
{
private string _some_value;
public string Value { get; set; }
public string SomeValue => _some_value; // getter always accessible
public Idea() => _some_value = "Hello World!";
public void SetSomeValue(string value)
{
// .... some logic
_some_value = value;
}
} However, If you like the assignment syntax or like to use some operators, I'd advise you to use public class Idea
{
private string _some_value;
public string Value { get; set; }
public Idea() => _some_value = "Hello World!";
public ref string SomeValue() => ref _some_value;
} Which can be used thus: Idea i = new Idea { Value = "value" };
i.SomeValue() = "42";
string s = i.SomeValue(); |
Beta Was this translation helpful? Give feedback.
2 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.
-
I would like to see a "not init" property which forbids a property being used during initialisation.
Often a property is only usable after initialisation. If used in initialisation it then becomes dependent on initialisation order.
public class Idea
{
public string Value { get; set; }
public string SomeValue { get; set; } // Depends upon Value being initialised
}
var Idea = new Idea // Works
{
Value = "XXXX",
SomeValue = "YYYY"
};
var Idea = new Idea // Won't Work
{
SomeValue = "YYYY", // Value not initialised
Value = "XXXX"
};
A "not init" property that forbids the property being used in initialisation would stop this happening.
public class Idea
{
public string Value { get; set; }
public string SomeValue { get; not init; } // Depends upon Value being initialised
}
Beta Was this translation helpful? Give feedback.
All reactions