2

consider follow simple class

public class SomeType
{
    public static int Fn(dynamic arg) { return 1; }            
}

and the follow statement

dynamic value = 10;
var a = SomeType.Fn(null);
var b = SomeType.Fn(value);

the type of a is correct ( int )

the type of b is wrong ( dynamic )

I can't use intellisense any more on b until I do a dummy recast (int)SomeType.Fn(value) for what was already prototype to return an integer.

the question is, why the dynamic in the argument makes the intellisense to change my function prototype signature ?

even if I insert a dynamic into a function, that function cannot return nothing else than what is declared in its prototype, is this a bug ?

current workaround for me is the following

var b = SomeType.Fn((object)value);
user2864740
  • 60,010
  • 15
  • 145
  • 220
Lorenzo Delana
  • 532
  • 5
  • 11

1 Answers1

2

There is an easy way to check whether this is an Intellisense bug: call a method that is not available for int. If the compiler gives the variable the type int, you'll get a compile-time error. If the compiler gives the variable the type dynamic, you'll get a run-time error.

dynamic value = 10;
var a = SomeType.Fn(null);
a.DoesNotExist();
var b = SomeType.Fn(value);
b.DoesNotExist();

If you try this, you'll find that only a.DoesNotExist() causes a compile-time error.

In other words, the Intellisense behaviour you're seeing perfectly matches the compiler's behaviour, which is that a method call involving dynamic arguments has a dynamic result.

Your workaround isn't a workaround, it's a fix. When you have dynamic types, you're asking the compiler to ensure the expression is resolved at run-time. When you cast to object, you're taking the dynamic types out, and at that point the compiler will fully resolve the expression at compile-time again.