Create an extension method (which does work with null
arguments).
I named it Eq
for brevity (but kept it internal
so it doesn't confuse external consumers of your code)
internal static class StringExtensions
{
/// <summary>Performs a <see cref="StringComparison.CurrentCultureIgnoreCase"><c>CurrentCultureIgnoreCase</c></see> equality check.</summary>
public static Boolean Eq( this String x, String y )
{
return String.Equals( x, y, StringComparison.CurrentCultureIgnoreCase );
}
}
Used like so:
if( stringX.Eq( stringY ) ) {
}
Extension methods also work with null
values without throwing a NullReferenceException
:
String x = null;
String y = null;
if( x.Eq( y ) )
{
// this will run without exceptions
}
For C# 8.0+ and latter with nullable-reference-types, you can improve the method with attributes, for example:
using System.Diagnostics.CodeAnalysis;
internal static class StringExtensions
{
/// <summary>Performs a <see cref="StringComparison.CurrentCultureIgnoreCase"><c>CurrentCultureIgnoreCase</c></see> equality check.</summary>
[returns: NotNullIfNotNull("x")]
public static Boolean? Eq(
this String? x,
String? y
)
{
if( x is null ) return null;
return String.Equals( x, y, StringComparison.CurrentCultureIgnoreCase );
}
}
Or:
using System.Diagnostics.CodeAnalysis;
internal static class StringExtensions
{
/// <summary>Performs a <see cref="StringComparison.CurrentCultureIgnoreCase"><c>CurrentCultureIgnoreCase</c></see> equality check. Always returns false when <param ref="x"/> is null.</summary>
public static Boolean Eq(
[NotNullWhen(true)] this String? x,
[NotNullWhen(true)] String? y
)
{
if( x is null ) return false;
return String.Equals( x, y, StringComparison.CurrentCultureIgnoreCase );
}
}
That way the compiler can use this Eq
method to also determine the null
-state of x
(assuming you're okay with null.Eq( null ) == false
, just like in SQL):
String? x = "foo" // or `null`;
String? y = "bar" // or `null`;
if( x.Eq( y ) )
{
SomeMethodThatRequiresNonNullArgs( x ); // the compiler knows `x` and `y` are non-null here.
}