3

I'm a newbie in c# and would like to ask you something, please help.

I created a variable with 3 persons inside using anonymous classes like this:

var personas = new[] { 
                new {nombre = "Guillermo", apellido = "Pérez", edad = 37}
                , new {nombre = "Juan", apellido = "García", edad = 27}
                , new {nombre = "Maria", apellido = "Rosina", edad = 47}
            };

Now, I tried to iterate on each of these items and I did (using the following code)

for (int i = 0; i < personas.Length; i++)
{
    var persona = personas[i];
    Console.WriteLine("{0} {1} tiene {2} años.", persona.nombre, persona.apellido, persona.edad);
}

THE PROBLEM comes when I want to create a method to do what I did with the last piece of code, the idea is to create a method and pass this object (in this case personas) to the method and do the loop inside. What I did is this:

 showPersonas(personas);

 static void showPersonas(object[] personsList)        {

        for (int i = 0; i < personsList.Length; i++) {
            var algo = personsList[i];
            Console.WriteLine(personsList[i].nombre); ----> ERROR!!

        }
    }

What I would like the method to do is to do what I did with the for loop, to be able to receive the object, iterate and print each item.

THANK YOU! for all your attention.

3
  • 1
    Do you have an argument for not creating a concrete class instead of the anonymous object? Seems this would all be solved with a simple class implementation. Your method names already describe what kind of object you should be receiving, so I personally don't think an anonymous type is the way to go here. Commented Nov 8, 2016 at 19:11
  • Considering the custom class would be less than 10 lines of code I see no reason to sacrifice compile-type safety by using dynamic or reflection. Create a class and use as array (or IEnumerable<>) of that as the type of your input parameter. Commented Nov 8, 2016 at 19:16
  • THANK YOU! Yes, the reason is that I'm learning about arrays, so they did put an example using an array of anonymous classes... and it works well if I do the loop in the same block of code, but if I try to create a method to loop thru then the problem start, as I don't know what these classes are... :-( Commented Nov 8, 2016 at 22:02

2 Answers 2

5

I see two options

Best option on my opinion is creating class Person. With created type compiler will show error during compiling time if you make typo while writing property name of will try to rename it later.

public class Person
{
    public string Nombre { get: set; }
    public string Apellido { get: set; }
    public string Edad { get: set; }
}


static void showPersonas(Person[] personsList)        
{
    foreach (var algo in personsList) 
    {
        Console.WriteLine(algo.nombre);
    }
}

Another option: dynamic keyword.
But be careful - with dynamic keyword you move type checking to the runtime. Which will throw same exception, which you now getting in compile time, during runtime.

static void showPersonas(dynamic[] personsList)        
{
    for (int i = 0; i < personsList.Length; i++) 
    {
        var algo = personsList[i];
        Console.WriteLine(algo.nombre);

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

5 Comments

If you have two options and prefer one of them I would say it's better to give that one first. e.g. "Personally I would do X but you could do Y".
@DStanley - changed as you suggested, but I always was sure, that people better remember last thing :)
that's a good point. I am always afraid they will take the first answer and stop reading, but you may be right. I still upvoted and I appreciate the consideration.
Thanks for your prompt answers... yes I could do a strong typed class, and I would prefer that but, without doing a class, using the exact same anonymous class is it possible?
Yes it is possible - see another option of my answer with using dynamic keyword.
0

As for the answer you can do it like this:

static void showPersonas(dynamic[] personsList){

    for (int i = 0; i < personsList.Length; i++){
        var algo = personsList[i];
        Console.WriteLine(personsList[i].nombre);

    }
}

Be aware what dynamic will throw exceptions if field not presented in your objects.

As for the BEST way to do this, just create class for this object and use it. You see, C# is not designed as javascript or python and should not be ever used like one.

It is strong typed language and in my opinion this is advantage.

1 Comment

THANKS FOR YOUR ANSWER... I'm not trying to use javascript or phyton, I'm just learning from my book... they told me I could do anonymous classes, enumerations and structures, and now I'm learning how to do arrays... so my idea was to practice array loops... :-)

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.