Object - NullIf
A T extension method that null if.
public static void Main() { string str = "1"; // C# Extension Method: Object - NullIf string result1 = str.NullIf(x => x == "1"); // return null; string result2 = str.NullIf(x => x == "2"); // return "1"; Console.WriteLine(result1); Console.WriteLine(result2); }
View Source
using System; public static partial class Extensions { /// <summary> /// A T extension method that null if. /// </summary> /// <typeparam name="T">Generic type parameter.</typeparam> /// <param name="this">The @this to act on.</param> /// <param name="predicate">The predicate.</param> /// <returns>A T.</returns> public static T NullIf<T>(this T @this, Func<T, bool> predicate) where T : class { if (predicate(@this)) { return null; } return @this; } }