about use Lambda expression in Property

兰树豪 361 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; 
        }

.NET Standard
.NET Standard
A formal specification of .NET APIs that are available on multiple .NET implementations.
509 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
1,224 questions
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,384 questions
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
3,247 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
8,316 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 37,831 Reputation points
    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;
        }
    }