Last active
January 23, 2020 11:34
-
-
Save oleksabor/b1e186be0b80f5e6f64c585535315d8f to your computer and use it in GitHub Desktop.
how to return anonymous type from method https://stackoverflow.com/questions/59874640/resolving-an-anonymous-type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyController | |
{ | |
public object Get(string id) | |
{ | |
return new { Key = id, Value = "val:" + id }; | |
} | |
} | |
class Program | |
{ | |
// Application entry-point | |
static void Main() | |
{ | |
var sut = new MyController(); | |
// Act. | |
dynamic res = sut.Get("42"); | |
// Second attempt: | |
var a = new { Key = "", Value = "" }; | |
a = Cast(a, res); // <- the code works | |
Console.WriteLine($"{a.Key} {a.Value}"); | |
} | |
private static T Cast<T>(T typeHolder, object x) | |
{ | |
// typeHolder above is just for compiler magic | |
// to infer the type to cast x to | |
return (T)x; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment