Arseni Mourzenko
Arseni Mourzenko

Reputation: 52321

Is there a language construct similar to PHPs list() in C#?

PHP has a language construct list() which provides multiple variables assignment in one statement.

$a = 0;
$b = 0;
list($a, $b) = array(2, 3);
// Now $a is equal to 2 and $b is equal to 3.

Is there a similar thing in C#?

If not, is there any workaround which may help to avoid code like the following, without having to deal with reflection?

public class Vehicle
{
    private string modelName;
    private int maximumSpeed;
    private int weight;
    private bool isDiesel;
    // ... Dozens of other fields.

    public Vehicle()
    {
    }

    public Vehicle(
        string modelName,
        int maximumSpeed,
        int weight,
        bool isDiesel
        // ... Dozens of other arguments, one argument per field.
        )
    {
        // Follows the part of the code I want to make shorter.
        this.modelName = modelName;
        this.maximumSpeed = maximumSpeed;
        this.weight= weight;
        this.isDiesel= isDiesel;
        /// etc.
    }
}

Upvotes: 3

Views: 167

Answers (4)

Inverseofverse
Inverseofverse

Reputation: 344

Yes - you can eliminate all the code in the constructor with object initializers (new for C# 3.0). Here is a pretty good explanation:

http://weblogs.asp.net/dwahlin/archive/2007/09/09/c-3-0-features-object-initializers.aspx

Upvotes: 0

James Curran
James Curran

Reputation: 103525

"Multiple variable initialization" or "Multiple variable assignment" ?

For initialization

$a = 0; 
$b = 0; 
list($a, $b) = array(2, 3); 

would be:

 int a=2, b=3;

For assignment, there's no shortcut. It has to be two statement, but if you like, you can put the two statements on one line:

 a=2; b=3;

Upvotes: 1

Kris van der Mast
Kris van der Mast

Reputation: 16613

I think you're looking for object and collection initializers.

var person = new Person()
{
    Firstname = "Kris",
    Lastname = "van der Mast"
}

for example where Firstname and Lastname are both properties of the class Person.

public class Person
{
    public string Firstname {get;set;}
    public string Lastname {get;set;}
}

Upvotes: 2

mqp
mqp

Reputation: 71945

No, I'm afraid there isn't any good way to do that, and code like your example gets written often. It sucks. My condolences.

If you're willing to sacrifice encapsulation for concision, you can use object initializer syntax instead of a constructor for this case:

public class Vehicle
{
    public string modelName;
    public int maximumSpeed;
    public int weight;
    public bool isDiesel;
    // ... Dozens of other fields.
}

var v = new Vehicle {
    modelName = "foo",
    maximumSpeed = 5,
    // ...
};

Upvotes: 5

Related Questions