Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortcut for creating constructor with variables (C# Visual Studio 2010)

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;
}
like image 968
Markus Avatar asked Jan 17 '12 11:01

Markus


People also ask

What is the shortcut to create constructor?

Press Ctrl+. to trigger the Quick Actions and Refactorings menu. Select Generate constructor in <QualifiedName> (with properties).

Can we initialize a variable without constructor?

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.

How do you call multiple constructors in C#?

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.


2 Answers

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:

enter image description here

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.

like image 126
Marc Gravell Avatar answered Oct 13 '22 00:10

Marc Gravell


If you are using ReSharper the shortcut is Alt + Insert.

Source

like image 41
IndieTech Solutions Avatar answered Oct 13 '22 00:10

IndieTech Solutions