How to Return Status in C#

I use the design pattern of returning a Status in a tuple with the exception or actual result I need to return like this,

return (Status.Success, result);

You don’t have to go “all out” like this Status example (I got bored one day).

Basically 0 is none, neutral, or unknown.
Anything less than 0 is a type of error.
And anything higher than 0 would be a type of success.

Example:

	public enum Status : Int16 {

		Fatal = -Flawless,

		Exception = Error - 1,

		Error = Warning - 1,

		Warning = Skip - 1,

		Skip = -Continue,

		Timeout = Stop - 1,

		Stop = -Start,

		Halt = -Proceed,

		Done = Negative - 1,

		Negative = No - 1,

		No = -Yes,

		Bad = -Good,

		Failure = -Success,

		Unknown = 0,

		None = Unknown,

		Success = 1,

		Okay = Success,

		Good = Okay,

		Yes = Good,

		Positive,

		Continue,

		Go,

		Start,

		Proceed,

		Advance,

		Flawless

	}

And some Status extensions I use.

	public static class StatusExtensions {

		static StatusExtensions() {
			if ( Status.Good.IsBad() ) {
				throw new InvalidOperationException( "Someone blinked." );
			}

			if ( Status.Failure.IsGood() ) {
				throw new InvalidOperationException( "Someone blinked." );
			}

			if ( Status.Success.IsBad() ) {
				throw new InvalidOperationException( "Someone blinked." );
			}

			if ( !Status.Unknown.IsUnknown() ) {
				throw new InvalidOperationException( "Someone blinked." );
			}
		}

		[Pure]
		[MethodImpl( MethodImplOptions.AggressiveInlining )]
		public static Boolean Failed( this Status status ) => status <= Status.Failure;

		[Pure]
		[MethodImpl( MethodImplOptions.AggressiveInlining )]
		public static Boolean IsBad( this Status status ) => status.Failed();

		[Pure]
		[MethodImpl( MethodImplOptions.AggressiveInlining )]
		public static Boolean IsGood( this Status status ) => status.Succeeded();

		[Pure]
		[MethodImpl( MethodImplOptions.AggressiveInlining )]
		public static Boolean IsUnknown( this Status status ) => status == Status.Unknown || !status.IsBad() && !status.IsGood();

		[Pure]
		[MethodImpl( MethodImplOptions.AggressiveInlining )]
		public static Boolean Succeeded( this Status status ) => status >= Status.Success;

		[Pure]
		[NotNull]
		public static String Symbol( this Status status ) => status.GetDescription() ?? Symbols.Null;

		[Pure]
		[MethodImpl( MethodImplOptions.AggressiveInlining )]
		public static Status ToStatus( this Boolean status ) => status ? Status.Success : Status.Failure;
	}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s