When you add an interface to a class, you can right-click the class and use the Implement Interface quick action to automatically implement the interface. By default, it implements members that throw exceptions, even the getters and setters:
public class Coder : IPerson
{
public string FirstName { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public string LastName { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public void DoWork()
{
throw new NotImplementedException();
}
}
Code language: C# (cs)
This is fine for methods, but you’d expect it to generate auto properties instead of properties that throw exceptions in the getters/setters.
Fortunately, this behavior is controlled by a setting in Visual Studio. You can change it to generate auto properties instead (without changing how it generates methods). Here’s how:
- In the Visual Studio menu, click Tools > Options
- In the options, navigate to Text Editor > C# > Advanced
- Scroll down and find the Implement Interface or Abstract Class section.
- Select prefer auto properties.
- Click OK.
Now when you use the Implement Interface quick action, it’ll generate auto properties:
public class Coder : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public void DoWork()
{
throw new NotImplementedException();
}
}
Code language: C# (cs)
Notice how the generated method still throws an exception. As mentioned, changing this setting doesn’t change how it generates method. At the end, you have good default behavior for both methods and properties.