Reputation: 3375
In Visual Studio 2010 C# you can, in a class, type ctor
and then press tab and Visual Studio will create a constructor for that class for me. It is very convenient.
But is there a way to make Visual Studio create a constructor with all my variables, properties and so on?
For example,
public class User
{
public String UserName { get; private set; }
}
And for this I want ctor
+ tab to make me a
public User(string UserName)
{
this.UserName = UserName;
}
Upvotes: 12
Views: 44474
Reputation: 2541
If you are using ReSharper the shortcut is Alt + Insert.
Upvotes: 2
Reputation: 1017
The "ctor" code snippet only creates a blank constructor, but does not use the existing attributes of the class in this constructor.
However, the latest versions of ReSharper enables you to choose the fields to be included in a constructor (like Eclipse does since a long time ago).
Upvotes: 2
Reputation: 3375
Thanks to Samuel Slade (telling me it's called code-snippets) I managed to find another Stack Overflow answer: Snippet code to create constructor in VS2010 Express
And it seems as the answer is NO, not without a plugin/extension.
Many refer to the ReSharper extension.
Upvotes: 4
Reputation: 1958
Use ReSharper's ctorf.
This will allow you to create a constructor with generated arguments based on fields defined in the class.
Upvotes: 0
Reputation: 609
I think you could do this with a snippet:
See Creating and Using IntelliSense Code Snippets (MSDN)
Upvotes: 1
Reputation: 1352
As others have noted, it is not possible to create snippets that are that intelligent.
There is a free Visual Studio add-in called Comet which can do what you want.
Upvotes: 1
Reputation: 1062745
You can sort of do this the other way around; if you start without the constructor or field, and try to use the non-existent constructor, you can press ctrl+. to ask it to generate one for you, usage-first:
This compiler then generates something not too dissimilar:
public class User
{
private string username;
public User(string username)
{
// TODO: Complete member initialization
this.username = username;
}
}
You can then fix this up manually if needed (perhaps using the inbuilt rename refactor, etc). But not quite what you wanted.
Upvotes: 15
Reputation: 8613
I think what you are referring to is Code Snippets. You can write your own Code Snippets (they are written in XML). See here for a starting point.
You should also be able to edit existing Code Snippets (such as the ctor
one). Refer to MSDN for some direction on this.
Note: Further Googling on Code Snippets will bring up more tutorials and references.
Upvotes: 10