In C# 6.0 I can write:

public int Prop => 777;

But I want to use getter and setter. Is there a way to do something kind of the next?

public int Prop {
   get => propVar;
   set => propVar = value;
  • 2
    No, only getters... – Jeff Mercado Apr 2 '16 at 11:14
  • 1
    What problem are you trying to solve here? This only makes sense to me if you don't add any more complicated logic than simply loading/storing the value from/to a field, at which point auto-implemented properties would already cover your need. What type of implementation do you have in mind that is so short that the => syntax is worth it, but yet too complicated for auto-implemented properties? – user743382 Apr 2 '16 at 11:27
  • 3
    Why don't you use an auto property? – slugster Apr 2 '16 at 11:38
  • 1
    It's not uncommon to need to map a property to something else, when implementing an interface for example. The expression body style just keeps things compact. – OlduwanSteve Oct 3 '17 at 8:37

First of all, that is not lambda, although syntax is similar.

It is called "expression-bodied members". They are similar to lambdas, but still fundamentally different. Obviously they can't capture local variables like lambdas do. Also, unlike lambdas, they are accessible via their name:) You will probably understand this better if you try to pass an expression-bodied property as a delegate.

There is no such syntax for setters in C# 6.0, but C# 7.0 introduces it.

private int _x;
public X
    get => _x;
    set => _x = value;

C# 7 brings support for setters, amongst other members:

More expression bodied members


class Person
    private int id = GetId();

    ~Person() => names.TryRemove(id, out _);              // finalizers
    public string Name
        get => names[id];                                 // getters
  • @Achilles1515 thanks for the edit, the source snippet was updated to correct this after I posted the answer. I also updated the out variable name to match the current version of the source snippet. – user247702 Aug 9 '18 at 13:37

There is no such syntax, but the older syntax is pretty similar:

    private int propVar;
    public int Prop 
        get { return propVar; }
        set { propVar = value; }


public int Prop { get; set; }
  • 4
    This is demonstrably not true, as the answers above indicate. – codeMonkey Jan 2 at 18:21

Your Answer

