Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Note that returning anonymous types or <code>Tuple&lt;&gt;</code> from a method is a bad thing to do</strong> </p> <p>But you asked a question about how to do it, not about "is it a good idea"...</p> <p>By using dynamic or reflection...</p> <pre><code>dynamic b = Test(); string str = b.A; </code></pre> <p>Or by cheating:</p> <pre><code>public static object Test() { return new { A = "Test" }; } public static string GetA(object obj) { // We create an anonymous type of the same type of the one in Test() // just to have its type. var x = new { A = string.Empty }; // We pass it to Cast, that will take its T from the type of x // and that will return obj casted to the type of the anonymous // type x = Cast(x, obj); // Now in x we have obj, but strongly typed. So x.A is the value we // want return x.A; } public static T Cast&lt;T&gt;(T type, object obj) where T : class { return (T)obj; } string str = GetA(Test()); </code></pre> <p>In C# all the anonymous types with the same properties of the same type that are in the same assembly are merged together. So the <code>new { A }</code> of <code>Test()</code> and of <code>GetA()</code> are of the same type.</p> <p>The <code>Cast&lt;T&gt;</code> is a useful trick to extract the type from an anonymous type. You pass as the first parameter your typed anonymous type (the parameter is used only to "activate" the generic <code>T</code>) and as the second parameter the object you want to cast. Similar tricks can be used to create collections of generic types, like</p> <pre><code>public static T MakeList&lt;T&gt;(T type) { return new List&lt;T&gt;(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload