Allow throw
expressions in a property's initial value
#9040
-
A bit of an unusual one, I think there could be value in allowing the following syntax for properties: public class C
{
public string Val { get; set; } = throw new Exception("Val has not been set");
} The idea is that getting this property will throw an exception if its setter was never called, roughly equivalent to the following hand-written code: public class C
{
private bool Val_setter_called = false;
private string Val_backing_field = null;
public string Val
{
get
{
if (!Val_setter_called)
throw new Exception("Val has not been set");
return Val_backing_field;
}
set
{
Val_setter_called = true;
Val_backing_field = value;
}
}
} This is partly inspired by Powershell, where a similar syntax is allowed on function arguments: function Foo($val = $(throw "Val was not provided"))
... This would be useful anywhere a type is expected to be deserialized (and therefore something like the I understand this suggestion might be controversial, but I still thought it was worth putting out there. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Feels like something a source generator and a partial property could do pretty easily? |
Beta Was this translation helpful? Give feedback.
Feels like something a source generator and a partial property could do pretty easily?