📜 ⬆️ ⬇️

Anonymous types outside the function

Anonymous types are a very nice extension to C #, which appeared in version 3.0. With the help of anonymous types we can on the fly create a storage object and fill it with data.
The main use of anonymous types is, of course, LINQ. In fact, they were created for him (in general, all the innovations of C # 3.0 were made for LINQ, with the exception, perhaps, of partial methods).
var o = new {Bar=2, Foo= "string" };


However, we will not be able to use this object outside the method in which it was declared and initialized:
??? GetFullName()
{
return new {Name="", Surname=""};
}

object PrintFullName()
{
var fullname = GetFullName() as ???;
}

??? GetFullName()
{
return new {Name="", Surname=""};
}

object PrintFullName()
{
var fullname = GetFullName() as ???;
}


In fact, we do not know which type should be used instead of ??? .. However, there is another, not quite obvious way to use anonymous types - as keys for a Dictionary:
Dictionary < object , string> dict = new Dictionary < object , string>();
public void Add ()
{
dict. Add ( new {x=5, y=6}, "test");
}

public void Get (){
Console.WriteLine(dict[ new {x=5, y=6}]);
}
* This source code was highlighted with Source Code Highlighter .
Dictionary < object , string> dict = new Dictionary < object , string>();
public void Add ()
{
dict. Add ( new {x=5, y=6}, "test");
}

public void Get (){
Console.WriteLine(dict[ new {x=5, y=6}]);
}
* This source code was highlighted with Source Code Highlighter .

This is possible because the compiler-generated shells for anonymous types implement the Equals () and GetHashCode () methods. However, the same problem remains - we will not be able to get values ​​from such a key, because again we will not be able to explicitly indicate its type, therefore, the use of the key is limited only by the methods Get (), Set () and ContainsKey ().
So, if you need to organize data storage in a Dictionary with a complex key consisting of several fields, and you don’t need to get the values ​​of this key, feel free to use anonymous types.

')

Source: https://habr.com/ru/post/37170/


All Articles