Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create auto implemented properties when implementing an interface into a class?

When I implement an interface for the first time into a class I want either resharper 6 or visual studio 2010 to implement my properties as auto implemented properties and not put in the default value of throw new NonImplementedException();. How can I do this? For example:

public interface IEmployee
{
// want this to stay just like this when  implemented into class
ID { get; set; }
}

public class Employee : IEmployee
{
// I do not want the throw new NonImplemented exception
// I want it to just appear as an auto implemented property
// as I defined it in the interface
public int ID
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }
}

Because this happens all the time, I am finding myself having to constantly refactor and manually remove those throw new UnImplimented() exceptions and manually make the properties be auto implemented... a pain! After all, I defined it as an auto implemented property in my interface.

Any help or advice much appreciated! Thanks.

like image 283
Frekster Avatar asked Apr 29 '12 12:04

Frekster


People also ask

What are auto-implemented properties?

Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property.

Can we create properties in interface C#?

Interfaces can contain properties and methods, but not fields/variables. Interface members are by default abstract and public. An interface cannot contain a constructor (as it cannot be used to create objects)

Can properties be declared inside an interface?

An interface can contain declarations of methods, properties, indexers, and events. However, it cannot contain instance fields.


1 Answers

Note: your R# keyboard shortcuts may differ, I am using the Resharper 2.x keyboard schema.

If you declare the interface on the class and then use Alt+Enter and select “Implement members”:

Selecting “Implement mebers”

Then you will get the default implementation, which happens to be throwing NotImplementedException, unless you change that.

But if you ignore the suggested course of action and instead use Alt+Insert to open the Generate menu, you can select “Missing members”:

Selecting “Missing members”

This will open Generate window, where you can select to implement the property (or properties) as auto-implemented:

Generate window

That will do exactly what you want:

class Employee : IEmployee
{
    public int Id { get; set; }
}
like image 155
svick Avatar answered Nov 09 '22 23:11

svick