Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension functions does not work for dynamic objects [duplicate]

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'

like image 649
Ashkan Mobayen Khiabani Avatar asked Dec 10 '22 16:12

Ashkan Mobayen Khiabani


1 Answers

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)

like image 92
Marc Gravell Avatar answered May 11 '23 16:05

Marc Gravell