C# Possible to have a generic return type?

Posted by JL on Stack Overflow See other posts from Stack Overflow or by JL
Published on 2010-06-03T11:23:06Z Indexed on 2010/06/03 11:24 UTC
Read the original article Hit count: 133

Filed under:

Here is a typical function that returns either true/false;

private static bool hasValue() { return true; }

Now on an error, I would like to return my own custom error object with definition:

public class Failure
    {
        public string failureDateTime { get; set; }
        public string failureReason { get; set; }
    }

I would have expected to be able to throw this custom object for example...

private static bool hasValue()
{
    throw new Failure(); 
}

This is not possible, and I don't want to derive Failure from System.IO.Exception because of the inability to serialize an exception in C#.

What is the best practice / or ideal solution to this problem. Should I just work with private static object? Or is there a cleaner way to return a custom object or bypass the typical return type on an error (not using System.IO.Exception)?

Not entirely wild about object either, because then I need to cast the result and validate it by more boolean logic.

© Stack Overflow or respective owner

Related posts about c#