I'm learning C# and I'm trying to understand how functions with dynamic params works and I have the following example:
Type[] GetTypes(params object[] args)
{
Type[] types = new Type[args.Length];
for (int i = 0; i < args.Length; i )
{
types[i] = args.GetType();
Console.WriteLine(types[i].ToString());
}
return types;
}
void MyFunction(params object[] args)
{
foreach (var type in GetTypes(args))
{
Console.WriteLine(type.ToString());
}
}
MyFunction(56, true, 45.9, "testing types deduction");
The problem I dound here is that the deduction is not correctly cause the output is:
>System.Object[]
>System.Object[]
>System.Object[]
>System.Object[]
>System.Object[]
>System.Object[]
>System.Object[]
>System.Object[]
And was expecting something like
>System.Int32
>System.Bool
>System.Double
>System.String
>System.Int32
>System.Bool
>System.Double
>System.String
Is there any way to fix this or there is a different way to get the specific type received by parameter in args?
CodePudding user response:
You mistakenly wrote types[i] = args.GetType();
when you should have written types[i] = args[i].GetType();
.