Lets say I have this class:
public class LocalizableString
{
public string LocalizableString
{
get { return this.translatedString; }
}
string translatedString;
public LocalizableString(string input)
{
translatedString = input;
}
}
Which that code doesn’t work, but it highlight what I want to do.
I want to be able to go
LocalizableString newString = new LocalizableString(“Hello”);
but instead of having to go
newString.translatedString; to get the value
I would like to just go
newString;
or
newString();
and have it return what is held in the translatedString variable. Is there anyway to do that?
override the ‘ToString()’ method and return ‘translatedString’. This will make that if it’s every converted to String, it will come out as whatever you return from ‘ToString()’.
Though implicitly expecting the conversion to string to call ToString is bad practice. And really what you want to do here in general is bad practice. ‘LocalizableString’ isn’t a ‘String’, and you want to write your code so that it reads like it IS a string, which it isn’t. This is bad as it’s hard to read all because you want to avoid having to write a couple extra characters.
Now if you need this to be done for any other prim type. Like say int or bool. Well you would want to look into IConvertible interface:
Note this is supposed to represent “conversion”. Not that you’re treating something as something it isn’t, but converting something to something that it isn’t. This is a ‘clean’ approach to it. And you’d usually say something like this in your code:
var obj = new MyWeirdType();
int i = Convert.ToInt(obj); //if MyWeirdType implements IConvertible, it will use said interface to convert.