3

I've got some basic code in Mvc Core 2 that is attempting to take advantage of the implicit conversion between T and ActionResult<T>.

    public ActionResult<IEnumerable<FrequentlyAskedQuestion>> Test()
    {
        IEnumerable<FrequentlyAskedQuestion> x = new FrequentlyAskedQuestion[0];
        return x;
    }

I get this error

2>Controllers\FaqsController.cs(57,20,57,21): error CS0029: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<Models.FrequentlyAskedQuestion>' to 'Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.IEnumerable<Models.FrequentlyAskedQuestion>>'

If I allow it to remain as an array it works.

    public ActionResult<IEnumerable<FrequentlyAskedQuestion>> Test()
    {
        var x = new FrequentlyAskedQuestion[0];
        return x;
    }

I can see the code of AspNetCore has this static implicit operator that would be nice for this to work

    public static implicit operator ActionResult<TValue>(TValue value)
    {
        return new ActionResult<TValue>(value);
    }
ocdi
  • 415
  • 4
  • 9
  • Your code is wrong. The correct one would be `ActionResult> x = new FrequentlyAskedQuestion[0];`, since the implicit conversion looks at the LEFT-hand operator (left of `=`). Since your left-hand type is `IEnumerable x = new FrequentlyAskedQuestion[0];` it won't invoke your overriden implicit override and when you just return the array it is used (since array implements `IEnumerable` – Tseng May 17 '18 at 06:08

0 Answers0