Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I automatically generate a constructor that receives and stores services for free?
    primarykey
    data
    text
    <h2>Problem</h2> <p>I regularly find myself manually typing out code that looks like this:</p> <pre><code>public class SomeClass { readonly ServiceA serviceA; readonly ServiceB serviceB; public SomeClass(ServiceA serviceA, ServiceB serviceB) { this.serviceA = serviceA.; this.serviceB = serviceB; } } </code></pre> <h2>Requirements</h2> <p>I would like to save time by having a way to generate as much of this as possible. I don't want to use a tool that requires a purchase. The only information that is variable here is the class name and the types of the services. So in this example, I would like to be to type something minimal like this:</p> <ol> <li><kbd>Some</kbd>+<kbd>Shortcut</kbd></li> <li><code>SomeClass</code></li> <li><code>ServiceA</code></li> <li><code>ServiceB</code></li> <li><kbd>Enter</kbd></li> </ol> <p>I'm also open to a solution that still requires me to type in the names of the fields. I don't mind whether or not the <code>private</code> access modifier is present in the field definitions, although I prefer to not have it since the code is a bit leaner that way. Similarly, I'm willing to accept a solution that doesn't generate read-only fields, but I do prefer them since I seldom want to change a service after my class is initialised.</p> <h2>What I've Tried</h2> <p>The quickest solution I know of at the moment is to type something like the following in another section of code and tell Visual Studio to create the class and constructor from its usage.</p> <pre><code>new SomeClass((ServiceA)null, (ServiceB)null); </code></pre> <p>However, I don't always work in this order; sometimes I want to create a class before using it. So what I typically do is this:</p> <ol> <li>Invoke the <code>ctor</code> code snippet.</li> <li>Fill in the constructor body.</li> <li>Use CodeRush Xpress to generate the fields. (It provides a way to generate read-only fields, whereas Visual Studio doesn't make them read-only.)</li> </ol> <p>Code-snippets work well, but I don't think they support variable numbers of parameters, so they're probably not suited to this problem.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload