Readable Properties

C # 6 introduced some new functions, including only getter auto-properties and property-like function members .

I am wondering what are the differences between these two properties? Is there any reason I would prefer each other?

public class Foo { public string Bar {get;} = "Bar"; public string Bar2 => "Bar2"; } 

I know that {get;} = can only be set when calling static or a constant value and that => can use instance instances. But in my particular case, which should I prefer and why?

+5
source share
1 answer

The easiest way to show them in terms of C # 1:

 public class Foo { private readonly string bar = "Bar"; public string Bar { get { return bar; } } public string Bar2 { get { return "Bar2"; } } } 

As you can see, the first includes a field, the second does not. So you usually use the first with something where each object can have a different state, for example. installed in the constructor, and the second with something that is constant in all objects of this type, so no state is required for each object (or where you simply delegate to other members, of course).

Basically, ask yourself which of the above code snippets would you write if you didn't have C # 6, and choose the appropriate C # 6 path.

+6
source

Source: https://habr.com/ru/post/1237195/


All Articles