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;
}
Press Ctrl+. to trigger the Quick Actions and Refactorings menu. Select Generate constructor in <QualifiedName> (with properties).
A constructor is typically used to initialize instance variables representing the main properties of the created object. If we don't supply a constructor explicitly, the compiler will create a default constructor which has no arguments and just allocates memory for the object.
A user can implement constructor overloading by defining two or more constructors in a class sharing the same name. C# can distinguish the constructors with different signatures. i.e. the constructor must have the same name but with different parameters list.
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.
If you are using ReSharper the shortcut is Alt + Insert.
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With