4

I have a Extension Function named ParseLong for string.

public static long ParseLong(this string x, long Default = 0) 
{ 
if (!string.IsNullOrEmpty(x)) 
     long.TryParse(x, out Default);
 return Default; 
}

And works fine:

long x = "9".ParseLong();

However for dynamic objects like:

dynamic x = GetValues();
x.StartValue.ToString().ParseLong();

generates the error:

'string' does not contain a definition for 'ParseLong'

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171

1 Answers1

13

Correct, extension functions do not work for dynamic objects. That is because the dynamic object, when being told to execute ParseLong, has no clue what using directives were in your C# code, so cannot guess what you want to do.

Extension methods are 100% a compiler feature (only); dynamic is primarily a runtime feature (although the compiler has to help it in places).

You could just cast, though, if you know the type:

long x = ((string)x.StartValue).ParseLong();

(which swaps back from dynamic to regular C#, so extension methods work)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900