StinkySocks
StinkySocks

Reputation: 924

Is there a shortcut for creating fields / properties from constructor inputs? (c#)

Say you have a constructor in a newly created class:

public MyClass( string input1, float input2)
{
}

Is there a shortcut to produce code analogous to this?

public string Input1 {get; set;}
public float Input2 {get; set;}

public MyClass(string input1, float input2)
{
    Input1 = input1;
    Input2 = input2;
}

Many thanks.

Upvotes: 0

Views: 64

Answers (2)

kevin
kevin

Reputation: 2213

Considering the fields (they are properties really) are public in your example, you don't actually need a constructor. You can initialize them when you construct a new instance:

var x = new SomeClass { input1 = "value1", input2 = 12345 };

Upvotes: 1

CSharpie
CSharpie

Reputation: 9467

It is possible that visual studio helps you out abit.

It works when the constructtor doesnt exist yet.

Just type:

SomeClass a = new SomeClass(input1, input2);

It will be underlined red as the constructor doesnt exist yet. Then Rightclick on the not yet existing Constructor and Click

Generate => Construcotr

The result will look like this:

string input1;
float input2;

public SomeClass(string input1, float input2)
{
    // Some comment i dont remember
    this.input1 = input1;
    this.input2 = input2;
}

edit It is possible, that this feature only exists in Premium / Ultimate edition. Not sure on that one.

Upvotes: 2

Related Questions