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 theCurrentCulture
, orInvariantCulture
, or some other?