Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is a question about the structure of C#.

I would like to know why an Anonymous Types in C#


var matrices = new[]
{

new {nombre="Madelson", Edad="20"},
new {nombre = "Mike" , Edad = "30"},
new {nombre = "Ana", Edad ="15"}


};

What I have tried:

They get print, with brakets:

{ nombre = Madelson, Edad = 20 }
{ nombre = Mike, Edad = 30 }
{ nombre = Ana, Edad = 15 }


Do you guys know why?


Thanks in advance :)
Posted
Updated 14-Jun-20 6:32am
Comments
George Swan 15-Jun-20 1:36am    
It's because, the default ToString method gets called for the anonymous type. I stand to be corrected on this, but my understanding is that the ToString method cannot be overridden with anonymous types. However, you can print out the array something like this
foreach(var matrix in matrices)
{
Console.WriteLine($"Name is {matrix.nombre} Age is {matrix.Edad}");
}
Maciej Los 15-Jun-20 3:28am    
Sounds like an answer.
Maciej Los 15-Jun-20 3:27am    
What method do you use to print data? Improve your question!

1 solution

 
Share this answer
 
Comments
Member 14836444 14-Jun-20 19:49pm    
I have read the documentation, what I mean is when you print them, they get printed with the brakets as well. For example:

var matrices = new[]
{

new {nombre="Madelson", Edad="20"}

};


The output on the console is:
{ nombre = Madelson, Edad = 20 }
Richard MacCutchan 15-Jun-20 4:11am    
That looks correct to me. If you print a single item the default is to display exactly what is contained in it. If the braces were not included then it would not be clear that the item is a single object with those properties.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900