In C# 6.0 a read-only property like this:
public string SomeProperty { get { return "sometext"; } }
can be rewritten in a more compact way:
public string SomeProperty => "sometext";
This feature is called “expression body”, but it has some limitations, e.g. the property is turned into field, it only works with read-only properties and not with constructors, deconstructor, getter, setter and so on.
C# 7.0 add all these constructs and then expands the usage of this feature.
Here’s an example, which was taken “as is” from the .Net blog without any test in development environment because by the time of the last released build of Visual Studio 2017 (15.0.26020.0) this new feature doesn’t work yet:
class Person { private static ConcurrentDictionary<int, string> names = new ConcurrentDictionary<int, string>(); private int id = GetId(); public Person(string name) => names.TryAdd(id, name); // constructors ~Person() => names.TryRemove(id, out *); // destructors public string Name { get => names[id]; // getters set => names[id] = value; // setters } }
562 thoughts on “C# 7.0 – #7. An improved expression body feature”
Comments are closed.