about use Lambda expression in Property

兰树豪 381 Reputation points
2023-05-20T03:55:32.0433333+00:00

Here's using Lambda in Property,


      public int MyProperty

        {

            get =>  myVar; 

            set => myVar = value; 

        }


but if I want multiple statements in seter or getter, hot to do that?or in this case only can use normal getter or setter?

        public int MyProperty
        {
            get => {return myVar ; OnPropertyChanged("MyProperty");} // this is worong , 
            set => myVar = value; 
        }

Developer technologies Windows Presentation Foundation
Developer technologies .NET Other
Developer technologies Visual Studio Other
Developer technologies C#
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-06-11T15:55:15.19+00:00

    While it uses the arrow syntax, you are not defining a lambda which is a type of closure, and a closure makes no sense as a property definition ( there is context to capture).

    As property definitions already support multi line definitions, the arrow syntax was added to support the common case of a single expression.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. don bradman 621 Reputation points
    2023-05-20T04:20:32.54+00:00

    If you want to include multiple statements in a property getter or setter, you cannot use the simple arrow notation that is commonly used with Lambda expressions. Instead, you need to use a block of code enclosed in curly braces.

    e.g.

    public int MyProperty
    {
        get
        {
            int result = 0;
            for (int i = 0; i < 10; i++)
            {
                result += i;
            }
            return result;
        }
        set => myVar = value;
    }
    
    // or
    
    public int MyProperty
    {
        get => myVar;
        set
        {
            if (value < 0)
            {
                throw new ArgumentException("Value must be non-negative");
            }
            myVar = value;
        }
    }
    
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.