Anonymous Types in C#

1 - What are anonymous types in C#

An anonymous type is a class that does not have a name, which means we don't have that class as such in the code. Most of the time, we use anonymous types when performing queries.

But we can also use them outside of queries. To create an anonymous type, all we need to do is use the new keyword.

var equipo = new { Nombre = "Real Betis", Ligas = 1 };

As we can see, the object we have created is an object called equipo that has two properties, Nombre and Ligas. When we assign a value to these properties, the compiler automatically detects what type they are going to be, based on the value we assigned to the property. In this case, Nombre will be a string and Ligas will be an int.

Later, if we want to access its properties, we just need to type the variable name and its property using the dot notation

string nombreEquipo = Equipo.Nombre;

1.1 - How to pass an anonymous type as a parameter

Before we continue, it's important to mention that passing anonymous types as parameters is not a good practice you should follow. Even so, there is a way to perform this action.

Anonymous types do not have a proper type, so in order to pass them to a different method, in that method we must use the dynamic type. However, this may cause many runtime errors, as the compiler will not check if the type you pass is correct.

public void test(dynamic equipo)
{
    var t = equipo.Nombre;
}

Once we have created the method and used the dynamic type, we can access its properties using the dot notation, just like with a regular object. Keep in mind that from now on, this object will not be checked to ensure the property exists, so for example, if we misspell the property or use a property that doesn't exist, we will get an error.

We will look at the dynamic type later in its own post.

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café