Ask a questionAsk a question
 

QuestionDynamic improvements on C# null-coalescing operator

  • Thursday, February 26, 2009 10:17 AMDave Sexton Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hi everyone,

    I haven't actually tried .NET 4.0 yet, but I'm wondering if something like the following code might be allowed by the C# compiler in 4.0 using dynamic and DLR overload resolution: 

    private void GetAndDisplayEmployee(string id)

    {

      DisplayResult(

        GetEmployee(id) ?? "Uh oh, bad id!"

        );

    }

     

    private void DisplayResult(Employee employee)

    {

      // TODO: Display employee

    }

     

    private void DisplayResult(string message)

    {

      // TODO: Display message

    }


    It seems that I often find myself in situations like these where use of the null-coalescing operator would be really slick, but a coercion requirement prevents it.  I guess the solution would be for the null-coalescing operator to return dynamic in these situations?

    - Dave
    http://davesexton.com/blog

All Replies

  • Monday, April 06, 2009 8:44 PMAlexandru Ghiondea - MSFT Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hi Dave

    Our current plan* is to have the ?? operator infer dynamic as the return type if any of the two operands are of type dynamic. So, if your GetEmployee() method returns dynamic, you should get the behavior you want.

    Hope this helps,

    Alex Ghiondea
    C# Compiler

    *the plan might change before RTM