In case you did not know, here is a C# trick which can make your code even more readable: the implicit keyword. This keyword can save you from doing explicit casts with many occasions.
Here is how it works:
class ImplicitClass
{
private readonly string _name;
private readonly string _value;
public ImplicitClass(string name, string value)
{
_name = name;
_value = value;
}
public static implicit operator string(ImplicitClass source)
{
return source._name;
}
public static implicit operator int(ImplicitClass source)
{
return Convert.ToInt32(source._value);
}
}
public class ImplicitTest
{
private void ImplicitTestMethod()
{
ImplicitClass implicitClass = new ImplicitClass("className", "2");
string name = implicitClass; // name becomes "className"
int value = implicitClass; // value becomes 2
}
}
Nice.
UPDATE: One of my fellow developers at Akcedo pointed out that the implicit operator does not make the code more readable, instead it makes it less readable. Only then I stopped and processed the implications, and... well, he is right.
The conclusion about the operator is: use it with care, always considering that it must be easy to understand. If the person who reads the assignment code (string name = implicitClass;) also needs to read the internal code of the operator (return source._name;) to understand what it does, you should not use an implicit operator.