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.
If there is any problem you can add a comment bellow or contact me in the website's contact form