C # Is it possible to have a common return type?

Here is a typical function that returns true / false;

private static bool hasValue()
{
    return true; 
}

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

public class Failure
    {
        public string FailureDateTime { get; set; }
        public string FailureReason { get; set; }
    }

I would expect you to be able to cast this custom object like ...

private static bool hasValue()
{
    try
        {
           ...do something
        }
    catch 
        {
         throw new Failure();
         }
    return true; 
}

This is not possible, and I do not want to throw Failure from System.IO.Exception, because I personally had problems with serializing exceptions in C # (this was with .net v2).

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

, , casting more boolean.

+5
7

:

var exception = new Exception();
exception.Data.Add("Failure", new Failure());
throw exception;

( ) . catch . , .

: , , ?

+10

Failure System.IO.Exception - #.

, , , IOException. . IOException Serializable. , , - .

IOException:

[SerializableAttribute]
[ComVisibleAttribute(true)]
public class IOException : SystemException
+7

System.Exception ( sealed), . , , , , .

Visual Studio , . , exception tab.

:

[Serializable]
public class MyException : Exception {
    public MyException() { }
    public MyException(string message) : base(message) { }
    public MyException(string message, Exception inner) : base(message, inner) { }
    protected MyException(
      System.Runtime.Serialization.SerializationInfo info,
      System.Runtime.Serialization.StreamingContext context)
        : base(info, context) { }
}
+6

+1

; , .

public class ValueResult
{
  public Failure FailureDetails {get;set;}
  public bool Success {get;set;}
  public bool HasValue {get;set;}
  public object Value {get;set;}
}

var result = HasValue();
if(result.Success)
  DoSomething(result.Value);
else if(!result.Success)
  LogFailure(result.FailureDetails);
0

, Exception :

[Serializable]
public class Failure: Exception
{
    public string ErrorMessage
    {
      get
       {
         return base.Message.ToString();
       }
    }

}

catch(Exception ex)
{
    throw new Failure(
          "exception message here", ex.messege);
}
0

All Articles