I recently had to perform some string replacements in .net and found myself developing a regular expression replacement function for this purpose. After getting it to work I couldn't help but think there must be a built in case insensitive replacement operation in .Net that I'm missing?

Surely when there are so many other string operations that support case insensitive comparission such as;

var compareStrings  = String.Compare("a", "b", blIgnoreCase);
var equalStrings    = String.Equals("a", "b", StringComparison.CurrentCultureIgnoreCase);

then there must be a built in equivalent for replace?

Update in .NET Core 2.0+ (August 2017)

This is natively available in .NET Core 2.0<sup>+</sup> with String.Replace which has the following overloads

public string Replace (string oldValue, string newValue, StringComparison comparisonType);
public string Replace (string oldValue, string newValue, bool ignoreCase, System.Globalization.CultureInfo culture);

So you can use either like this:

"A".Replace("a", "b", StringComparison.CurrentCultureIgnoreCase);
"A".Replace("a", "b", true, CultureInfo.CurrentCulture);

PS: You can browse .NET Core source if you want to see how MS implemented it


Legacy .NET Framework 4.8<sup>-</sup> option for VB Projects

Visual Basic has an Option Compare setting which can be set to Binary or Text

Setting to Text will make all string comparisons across your project case insensitive by default.

So, as other answers have suggested, if you are pulling in the Microsoft.VisualBasic.dll, when calling Strings.Replace if you don't explicitly pass a CompareMethod the method will actually defer to the Compare option for your file or project using the [OptionCompare] Parameter Attribute

So either of the following will also work (top option only available in VB , but both rely on VisualBasic.dll)

Option Compare Text

Replace("A","a","b")
Replace("A","a","b", Compare := CompareMethod.Text)