Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the type is System.Object here?

Here is some piece of code :

Func<dynamic> f1 = new Func<dynamic>(() => 10);
Func<int> f2 = () => 10;

Console.Write(f1.Method.ReturnType);
Console.Write(" and " + f2.Method.ReturnType );

Output : System.Object and System.Int32

My question is :

Why dynamic type inferred by DLR (type that is used for dynamic) here is System.Object and is not System.Int32 ? It's not very logical as it also involves boxing of the Int32 struct to object.

As far as i understand, when we check type here we do it dynamically on execution time because we use Reflection. So it's known to DLR by then that it's int but for some reason it boxes it into Object... Why?

I've tried to find anything regarding this on SO and googled for it but I couldn't find any answer that explains it all.

like image 963
Fabjan Avatar asked Dec 30 '25 01:12

Fabjan


1 Answers

Nothing is inferred here. It just doesn't know the type until it executes, and that is why the type given is object. The (static) compiler doesn't know the type since you don't know it yet. It is passed around as object and on the calling side it is dynamic again.

This is the same for regular methods:

Console.Write(typeof(Program).GetMethod("F1").ReturnType);

public static dynamic F1()
{
    return 10;
}

Output:

System.Object

like image 114
Patrick Hofman Avatar answered Jan 01 '26 20:01

Patrick Hofman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!