Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand for initializing members in class constructor

Tags:

c#

Let's say I have a class with many members like this

class someclass
{
    public int number {get;set;}   //repeated a dozen times, with different names of course
}

it's constructor should look like this

public someclass(int number, ...,)
{
    this.number=number;        //repeated again a dozen times
}

is there any shorthand notation to avoid the repetition in the constructor?

like image 522
Harter Avatar asked Nov 27 '25 12:11

Harter


1 Answers

You could use an object initializer:

var myInstance = new MyClass
                 {
                    Number = 42,
                    Foo = "Bar"
                 };
like image 91
CodeCaster Avatar answered Nov 29 '25 03:11

CodeCaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!