Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How ASP.NET Core APIs convert ActionResult<T> to T in action methods

Tags:

c#

.net-core

As an example look at below code which is a an API action:

[HttpGet("send")]
public ActionResult<string> Send()
{
    if (IsAuthorized())
    {
        return "Ok";
    }
    return Unauthorized(); // is of type UnauthorizedResult -> StatusCodeResult -> ActionResult -> IActionResult
}

My question is how this data conversion is happening here? How doesn't the compiler fail?

like image 999
jacksparrow92 Avatar asked Mar 03 '23 21:03

jacksparrow92


1 Answers

This is possible due to a language feature called operator overloading which allows for the creation of custom operators. ActionResult has such an implementation:

public sealed class ActionResult<TValue> : IConvertToActionResult
{
       public TValue Value { get; }

       public ActionResult(TValue value)
       {
            /* error checking code removed */
            Value = value;
       }

       public static implicit operator ActionResult<TValue>(TValue value)
       {
           return new ActionResult<TValue>(value);
       }
}

public static implicit operator I.e. this method provides the logic for TValue to be implicitly casted to type ActionResult. It's a very simple method that creates a new ActionResult with the value set to a public variable called Value. This method makes this legal:

ActionResult<int> result = 10; <-- // same as new ActionResult(10)

This essentially creates syntatic sugar for what you do in the Action methods to be legal.

like image 156
Avin Kavish Avatar answered Mar 30 '23 00:03

Avin Kavish