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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With