C# automatically apply ToLower to method string parameter?
c#, tolower
Solution
No, the C# compiler will not do this for you (why should it be tailored to such a specific requirement?), but you could get this done by writing a simple wrapper `struct` around `string`:
struct LowerCaseString
{
public LowerCaseString(string value)
{
this.value = value.ToLower();
}
private readonly string value;
public static implicit operator LowerCaseString(string value)
{
return new LowerCaseString(value);
}
public override string ToString()
{
return value;
}
… // perhaps implement IEquatable<>, IComparable<>, etc.
}
The implicit conversion operator allows you to then write code like this:
Foo("Hello world.");
void Foo(LowerCaseString text)
{
Console.WriteLine(text);
}
While this works as you would expect, there are some drawbacks with this approach:
a tiny (possibly negligible) performance hit, since a wrapper object must be instantiated around your string.
It might not be obvious to other users of your code that an implicit conversion operator exists, so they end up writing `new LowerCaseString("Hello world.")` instead. Looking at the class with Visual Studio's Object Browser would possibly resolve this issue if your team makes regular use of it.
this wrapper does not allow you to specify the `CultureInfo` used for `.ToLower()`. Do you want to use the `CurrentCulture`, or `InvariantCulture`, or some other?
Problem
Is there a way to make the C# compiler automatically apply ToLower() (or any other manipulating method invoke) to a particular method parameter before it gets used inside the method? //additional information: its purpose is to use a Dictionary with a case-insensitive key. Apparently, my first approach was completely wrong as I've already found a totally different approach that addresses the Dictionary itself, not the key it is accessed with. My bad! I should have provided you with that info. So, no further answers needed. Anyway, thanks a lot! Better approach in this particular case: c# Dictionary: making the Key case-insensitive through declarations