1

We have in PHP the jagged array declaration is like this:

<?php
$classmates = array ('Name' => array ('Bob', 'Jane', 'Jill'),
                    'Age' => array (18, 20, 23));

echo $classmates['Name'][1] . ' is ' . $classmates['Age'][1] . ' years old!';
?>

can we do same initialization of array in C#??

If yes than how? also tell me if it is possible to do with data type List?

1
  • The right way to do this will be to use a list of class objects. Commented Jun 1, 2013 at 2:17

1 Answer 1

2

Well, literally speaking, you could do something like this in C#:

    var arr = new Array[] { 
        new[] {"Bob", "Jane", "Jill"},
        new[] { 18,20,23 }};

I will say that it's probably not going to be a good idea. In C#, it's much better form to say something like this:

var arr = new[] { 
    new Person {Name = "Bob", Age = 18},
    new Person {Name = "Jane", Age = 20},
    new Person {Name = "Jill", Age = 23}};

or, if you're not into creating an actual Person class, you can use an anonymous class:

var arr = new[] { 
    new {Name = "Bob", Age = 18},
    new {Name = "Jane", Age = 20},
    new {Name = "Jill", Age = 23}};

What course you take depends on how you'll use the array, but suffice it to say that the first usage is not, for most use cases, considered to be a best practice.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.