PontusVarg
PontusVarg

Reputation: 29

Easier way to initialize multiple variables to the same value in a new object

Is there an easier way to do the write the following code when the values are the same?

SomeClass c = new SomeClass()
{
    var1 = someValue,
    var2 = someValue,
    var3 = someValue,
    var4 = someValue
}

Upvotes: 1

Views: 2669

Answers (3)

MDBarbier
MDBarbier

Reputation: 379

This sets all four variables to the same value:

string var1, var2, var3, var4;

var1 = var2 = var3 = var4 = "Hello World!";

All string variables contain "Hello World!" after execution.

Upvotes: 2

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89091

Or, use this behavior:

The result of an assignment expression is the value assigned to the left-hand operand

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/assignment-operator

And assign the properties like this:

var c = new someClass();
c.var1 = c.var2 = c.var3 = c.var4 = 4;

Upvotes: 2

servvs
servvs

Reputation: 74

You could make it a constructor parameter in the class.

someClass()
{
    type var1, var2, var3, var4;

    someClass(type someValue)
    {
        var1 = someValue;
        var2 = someValue;
        var3 = someValue;
        var4 = someValue;
    }
}

someClass c = new someClass(somevalue);

Upvotes: 0

Related Questions