UseCase: In recent code fixes, I observed that the developer did not take care of converting the case of strings uniformly before strings comparison and this has caused bugs in the production environment.
This triggered me a need to override the default Equals() method at namespace scope for already existing code where hundreds of places string comparisons are happening.
Before I go and fix manually at more than 400+ places, I was trying with these approaches, but could not find the satisfactory result.
Approach1:
Problem: It requires new method name -> NewEquals(). This requires changes in all the classes.We can't use 'Equals()' here as instance method takes higher precedence.
class Program
{
static void Main(string[] args)
{
string strFromConfig = "sometext";
const string str = "SomeText";
Console.WriteLine(str.Equals(strFromConfig)); // False
Console.WriteLine(str.NewEquals(strFromConfig)); // True
}
}
static class StringCompare // Extension method approach
{
public static bool NewEquals(this string str, string strconfig)
{
// edited this as per the suggestion in the comments.
return str.Equals(strconfig, StringComparison.OrdinalIgnoreCase);
}
}
Approach2:
Problem: Maybe I am making some mistake in overriding Equals().
Even if it works, it has one con that this overridden function won't be available within the namespace. And hence it won't fix in all the classes.
class Program
{
static void Main(string[] args)
{
string strFromConfig = "sometext";
const string str = "SomeText";
Console.WriteLine(str.Equals(strFromConfig)); // False
// This also doesn't invoke overridden method.
Console.WriteLine(str.Equals((object)strFromConfig)); // False
}
public override bool Equals(object obj)
{ // Program control doesn't enter here. So could not test the below two returns.
return base.Equals(obj);
//return base.ToString().ToLower().Equals(obj.ToString().ToLower());
}
}
Can someone please help me in knowing is it feasible to achieve what I am looking for -> One change - many fixes.