Here's some functional C# examples of extension methods. They can apply to both classes and structs.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace MyExtensions
{
public static class GuidExtensions
{
public static bool IsEmptyGUID(this Guid _This)
{
return (0 == Guid.Empty.CompareTo(_This));
}
}
public static class StringExtensions
{
public static bool IsEmptyOrWhiteSpace(this string _This)
{
if (_This is null) return false;
try
{
return (string.IsNullOrEmpty(_This) || string.IsNullOrWhiteSpace(_This));
}
catch (Exception ex)
{
throw new Exception($"StringExtensions.IsEmptyOrWhiteSpace() - Exception occurred!", ex);
}
}
public static bool StartsWithAny(this string _This, IEnumerable<string> PrefixesIn)
{
try
{
if (PrefixesIn?.Any() ?? false)
{
foreach (var prefix in PrefixesIn)
{
if (string.IsNullOrEmpty(prefix)) continue;
if (_This?.StartsWith(prefix, StringComparison.CurrentCulture) ?? false) return true;
}
}
return false;
}
catch (Exception ex)
{
throw new Exception($"StringExtensions.StartsWithAny() - Exception occurred!", ex);
}
}
public static bool StartsWithAny(this string _This, IEnumerable<string> PrefixesIn, StringComparison ComparisonTypeIn)
{
try
{
if (PrefixesIn?.Any() ?? false)
{
foreach (var prefix in PrefixesIn)
{
if (string.IsNullOrEmpty(prefix)) continue;
if (_This?.StartsWith(prefix, ComparisonTypeIn) ?? false) return true;
}
}
return false;
}
catch (Exception ex)
{
throw new Exception($"StringExtensions.StartsWithAny() - Exception occurred!", ex);
}
}
public static bool StartsWithAny(this string _This, IEnumerable<string> PrefixesIn, bool IgnoreCaseIn, CultureInfo CultureIn)
{
try
{
if (PrefixesIn?.Any() ?? false)
{
foreach (var prefix in PrefixesIn)
{
if (string.IsNullOrEmpty(prefix)) continue;
if (_This?.StartsWith(prefix, IgnoreCaseIn, CultureIn) ?? false) return true;
}
}
return false;
}
catch (Exception ex)
{
throw new Exception($"StringExtensions.StartsWithAny() - Exception occurred!", ex);
}
}
}
}
Usage example:
var g1 = Guid.Empty;
var g2 = Guid.NewGuid();
var rc = false;
rc = g1.IsEmptyGUID();
rc = g2.IsEmptyGUID();
var s1 = "Prefix";
var s2 = "Suffix";
string[] items1 = { "Any", "Old", "Word" };
string[] items2 = { "Pre", "Suf" };
rc = s1.StartsWithAny(items1);
rc = s1.StartsWithAny(items2);
rc = s2.StartsWithAny(items1);
rc = s2.StartsWithAny(items2);