Why C# lambda expression can't use instance properties and fields, when is used in a class scope? See this example:
public class Point:INotifyPropertyChanged
{
public float X {get; set;}
public float Y {get; set;}
PropertyChangedEventHandler onPointsPropertyChanged = (_, e) =>
{
X = 5;
Y = 5; //Trying to access instace properties, but a compilation error occurs
};
...
}
Why this is not allowed?
EDIT
If we can do:
public class Point:INotifyPropertyChanged
{
public float X {get; set;}
public float Y {get; set;}
PropertyChangedEventHandler onPointsPropertyChanged;
public Point()
{
onPointsPropertyChanged = (_, e) =>
{
X = 5;
Y = 5;
};
}
...
}
Why we can't initialize onPointsPropertyChanged
like a other fields inside the class scope?, for instancie: int a = 5
. The field onPointsPropertyChanged
always will be used after the constructor execute.
You cannot access an object instance before its constructor runs (such as in a field initializer or base constructor call).
This is true both inside a lambda and outside a lambda.
C# < 4 had a bug that allowed this in certain cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With