I am new to C# and .NET. I would like to know how I traverse an object that I am creating.
public ActionResult<Person> Get(int id)
{
var pipe = new searchClient();
var data = new[] {
new Person { id=1, Name="Ana", edad="24" },
new Person { id=2, Name="Joseph", edad="20" }
};
var looking = pipe.obtenerCliente(id, data);
return Ok(
looking
);
}
public class searchClient
{
public Object obtenerCliente(int id, Array data)
{
foreach(var d in data) {
Console.WriteLine(d); // Cuando recorro la matriz, me sale el contexto de los objetos
}
return data;
}
}
public class Person
{
public string Name { get; set; }
public string edad { get; set; }
public int id { get; set; }
}
When I go through the array with the foreach, in the console it returns the context of the Person object, I don't know how to continue going through that
The fact that you declare the parameters of the routine with a type that has no information about the type of elements, such as
Array
, which makes it necessary to apply type casts if you want to get to the members of each object in the array and the code is , in my opinion, more error-prone, since we skip the validations that the compiler does for us if we use strict types.Keeping the signature of the routine, you have to declare the variable type of the iterator element as
Persona
:Or you can leave implicit typing and apply the cast directly ad:
This does not prevent you from writing code that passes an array with elements of type
Car
and not to this routinePerson
, since we have stripped the compiler of the ability to check the type of the element.If you change the signature, you can receive an array of people, which makes things simpler and keeps us on the safe side with compiler validations:
Since there is now a type defined for the elements of
data
, even implicit typing would work:What happens to you here is that when you do this:
You are telling C# to print that object. Since that object inherits from object, even though you have given it properties, it doesn't know how it should be printed.
This is because the ToString method, as the documentation says, prints the full name of the object, which is not what you want, because you want it to print its content.
For that, here, you have two options:
write in the for each variable:
Override the ToString method in your class, so it knows how to print
In this case, inside your Person class, you should do:
That way, when you do:
it will print the name the age and the id...
Grades:
var d in data
, rather doperson d in data