It does not work this way, because it can only result in types known at compile time.
The dynamic
type can help you. However, you must know which operations the object supports. A small example:
class Program { static void Main(string[] args) { dynamic fooValue = Foo(); // тип возвращаемого значения заранее неизвестен Console.WriteLine(fooValue.Length); // выводит 5 dynamic barValue = Bar(); // тип возвращаемого значения заранее неизвестен Console.WriteLine(barValue.R); // выводит 255 } private static object Foo() { return "Hello"; } private static object Bar() { return Color.White; } }
You can also use reflection and query / set the required fields / properties / call methods first by getting a reference to them using Type.GetField()
/ Type.GetProperty()
/ Type.GetMethod()
, and then working using FieldInfo
/ PropertyInfo
. GetValue()
/ SetValue()
and MethodInfo.Invoke()
(which is less convenient, of course).