Constructor dependency code snippet in visual studio

If you have R# you can enter the field declarations and then highlight them and hit Alt-Enter which will give you the option to generate the constructor and field assignments.

enter image description here


I don't know about previous versions, but in vanilla Visual Studio 2017, you can actually add a constructor parameter

public SomeClass(ISomeService service)
{ 
}

Then put your cursor on service and from "Quick actions" you can chose Introduce and initialize field _someService which will do what you want :

private readonly ISomeService _someService;

public SomeClass(ISomeService service)
{ 
    _someService = service;
}

If you don't have Resharper, you can add the parameter on the constructor, write the assignament to an unexisting property and hit CTRL+. . This will prompt you with the options to automatically create a property or field for you.

For example, you have this class:

public class MyClass 
{ 
    public MyClass()
    { 
    }
}

You then add the parameter to the constructor, and the assignament:

public class MyClass 
{ 
    public MyClass(IDependency myDependency)
    { 
         this.myDependency = myDependency;
    }
}

And hit CTRL+. while on the asignament line, and select create field, and you'll get this:

public class MyClass 
{         
    IDependency myDependency;

    public MyClass(IDependency myDependency)
    { 
         this.myDependency = myDependency;
    }
}

Tags:

C#

.Net