0

Below is the sample code and it is throwing error (''string' does not contain a definition for 'ToUpperExtn'') during runtime. How can i handle this.

class Program
{
    static void Main(string[] args)
    {
        dynamic name = "Prasad";
        **Console.WriteLine(Convert.ToString(name).ToUpperExtn());** // Error: ''string' does not contain a definition for 'ToUpperExtn''

        string name1 = "Prasad";
        Console.WriteLine(name1.ToUpperExtn()); // Working fine
    }
}

public static class StringExtensions
{
    public static string ToUpperExtn(this string value)
    {
        return value.ToUpper();
    }
}
Prasad Kanaparthi
  • 6,423
  • 4
  • 35
  • 62
  • Possible duplicate of [Will the dynamic keyword in C#4 support extension methods?](https://stackoverflow.com/questions/258988/will-the-dynamic-keyword-in-c4-support-extension-methods) – Ben Cottrell Jul 23 '19 at 16:14
  • 2
    The following works however: `string s = Convert.ToString(name); Console.WriteLine(s.ToUpperExtn()); `. Interesting. – Klaus Gütter Jul 23 '19 at 16:15
  • And also `Console.WriteLine(Convert.ToString((object)name).ToUpperExtn());`. So the problem is that the compiler cannot deduce the type of the expression `Convert.ToString(name)` and the runtime resolutions does not consider extension methods. – Klaus Gütter Jul 23 '19 at 16:18
  • 1
    This already has been answered years ago: https://stackoverflow.com/questions/5311465/extension-method-and-dynamic-object – Kevin Cook Jul 23 '19 at 16:23

0 Answers0