Tuesday, January 6, 2009

C# 3.0 Automatic Property with private set method.

What if we need a automatic property with just a get method (read-only property), like this
public string Name { get; }

Compiler will throw error
"'Employee.Name.get' must declare a body because it is not marked abstract or extern. Automatically implemented properties must define both get and set accessors."

The reason being automatic property requires both get and set method defined. You can fix this error by defining the private set method for the property. By doing this, the property is still just a "getter".

public string Name { get; private set; }

No comments:

Post a Comment