Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why C# lambda expression can't use instance properties and fields?

Tags:

scope

c#

lambda

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.

like image 645
Raúl Otaño Avatar asked Jun 10 '13 18:06

Raúl Otaño


1 Answers

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.

like image 55
SLaks Avatar answered Nov 14 '22 21:11

SLaks