I see in the MSDN documentation of init keyword, it has code example as below, from the url: , from what I understand, the "YearOfBirth" in the beginning of the assignment "field = (YearOfBirth <= DateTime.Now.Year)" should be "value" keyword. Am I right? Or that is a new feature of a new C# version ? Thanks for your attention.
class Person_InitExampleFieldProperty
{
public int YearOfBirth
{
get;
init
{
field = (YearOfBirth <= DateTime.Now.Year)
? value
: throw new ArgumentOutOfRangeException(nameof(value), "Year of birth can't be in the future");
}
}
}
I see in the MSDN documentation of init keyword, it has code example as below, from the url: https://learn.microsoft/en-us/dotnet/csharp/language-reference/keywords/init, from what I understand, the "YearOfBirth" in the beginning of the assignment "field = (YearOfBirth <= DateTime.Now.Year)" should be "value" keyword. Am I right? Or that is a new feature of a new C# version ? Thanks for your attention.
class Person_InitExampleFieldProperty
{
public int YearOfBirth
{
get;
init
{
field = (YearOfBirth <= DateTime.Now.Year)
? value
: throw new ArgumentOutOfRangeException(nameof(value), "Year of birth can't be in the future");
}
}
}
Share
Improve this question
asked Nov 20, 2024 at 19:13
IcyBrkIcyBrk
1,2801 gold badge13 silver badges22 bronze badges
5
|
1 Answer
Reset to default -1Yes, what you show does work, with value
, but you also may find the alternative syntax more convenient and clear. Consider this very simplified example:
class InitOnlyDemo {
internal InitOnlyDemo() { CaseB = 42; }
int field = 0;
internal int CaseA {
get { return field; }
init { field = value; } }
internal int CaseB { get; init; }
public int CaseC { get; private protected set; }
}
Your case is the property CaseA
. With CaseB
, you rely on automatically implemented getter and then init
simply indicates “initialization-only” and leaves the initialization itself to the constructor. Finally, CaseC
uses automatically implemented getter and setter and also demonstrates a way to prescribe different access modifiers for getters and setters.
value
, as is, the test's result is always true sinceYearOfBirth
is 0 when the test is executed – vc 74 Commented Nov 20, 2024 at 19:46The field keyword is a preview feature in C# 13
. So, the code is correct and works as expected, but only in C#13 with preview features enabled. – Serg Commented Nov 20, 2024 at 20:13YearOfBirth
value, not the old one – vc 74 Commented Nov 21, 2024 at 17:33value
there. – Serg Commented Nov 21, 2024 at 18:38field
keyword? It could be something different: a private field with this name, (omitted by IcyBrk). Nothing prevents using this name. I followed the naming of the question and used this name in my answer. Of course, it works. – Sergey A Kryukov Commented Nov 24, 2024 at 0:49