How can we return an object that is different from the method return type?

Viewed 74

I don't understand why we can pass Customer while the return type is ActionResult<Customer>. How can we return an object that is different from the method return type?

However, I understand for Task<T> used for asynchronous methods, because c# language provides such a feature internally.

[HttpGet("{id}")]
public ActionResult<Customer> Get(string id)
{
    Customer cust = db.Customers.Find(id);
    if (cust == null)
    {
        return NotFound();
    }
    return cust;
}

Could you give me a simple example how to create our own Wrapper<T> to allow us to write something as follows?

public Wrapper<Foo> AnyMethod()
{
    return new Foo();
}
1 Answers

If you look at the source for ActionResult, you can see how it defines implicit conversion internally to allow it to wrap either some type T or ActionResult types. On similar lines, we can define a minimal Wrapper class like so:

public class Wrapper<T>
{
 private T _t;

 public Wrapper(T t)
 {
  _t = t;
 }

 public static implicit operator Wrapper<T>(T t)
 {
  return new Wrapper<T>(t);
 }
}
Related