ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ThrowIf

Just throw if you can

Source

using System;

namespace ThrowIf
{
    public static class Extensions
    {
        public static bool ThrowIfTrue(this bool value)
        {
            if(value)
                throw new ArgumentNullException();
            
            return value;
        }

        public static object ThrowIfFalse(this bool value)
        {
            return (!value).ThrowIfTrue();
        }

        public static object ThrowIfNull(this object o)
        {
            (o is null).ThrowIfTrue();
            
            return o;
        }

        public static object ThrowIfNotNull(this object o)
        {
            (o is null).ThrowIfFalse();
         
            return o;
        }
    }
}

Example

public interface ISoftDelete
{
    bool IsActive { get; set; }
}

public class Person : ISoftDelete
{
    public bool IsActive { get; set; }

    public Person()
    {
        IsActive.ThrowIfFalse();
    }
}

Author: Jan Okwalski

Submitted on: 16 okt. 2018

Language: C#

Type: ThrowIf

Views: 6507