title: Return object with Result T
body: <p>I need to return object values when I call methods. However, I also need to pass error messages along with these methods. As such I came up with an object like this:</p>
  
  <pre><code>public class ReturnObject
  {
      public bool Success { get; set; }
      public IEnumerable&lt;string&gt; Errors { get; set; }
      public dynamic Result { get; set; }
  }
  </code></pre>
  
  <p>Now from my services, I can call this and return whatever I want along with any errors. However, the problem is that this is not type safe and I need cast the Result every time. So my goal is to make it type safe. Here is how I came up with that:</p>
  
  <pre><code>public class ReturnObject&lt;T&gt;
  {
      public bool Success { get; set; }
      public IEnumerable&lt;string&gt; Errors { get; set; }
      public T Result { get; set; }
  }
  </code></pre>
  
  <p>Now, I return this object a lot, and as such, I Created a service which will return me the object. Trying to keep my code a bit dry. The service looks like this:</p>
  
  <pre><code>public class ResultService&lt;T&gt;
  {
      public ReturnObject&lt;T&gt; GetGoodResult(T result)
      {
          return new ReturnObject { Success = true, Result = result };
      }
  
  
      public ReturnObject&lt;T&gt; GetGoodResult(T result, IEnumerable&lt;string&gt; errors)
      {
          return new ReturnObject { Success = false, Errors = errors, Result = result };
      }
  }
  </code></pre>
  
  <p>So now lets says I have a service I want to use this from.</p>
  
  <pre><code>public class BookService
  {
      private ResultService&lt;book&gt; _resultServiceBook = new ResultService&lt;Book&gt;();
      private ResultService&lt;string&gt; _resultServiceString = new ResultService&lt;string&gt;();
  
      public ReturnObject&lt;Book&gt; GetBook() 
      {
          return _resultServiceBook.GetGoodResult(new Book());
      }
  
      public ReturnObject&lt;string&gt; GetBookName(bookId)
      {
          return _resultServiceString.GetGoodResult(GetBookNameFromRepo(bookId));
      }
  }
  </code></pre>
  
  <p>As you can see, for every type that I want to return, I have to create a new instance of ResultService with that type.  I can't seem to find a better way to accomplish this. I don't like that I have to create the same service multiple times like this to keep it type safe.</p>
  
  <p>Just in case it is not clear what I mean when I say type safe, I mean that visual studio will catch type comparison while I'm still coding.</p>