Hullo,
For example if I had:
public class Fu
{
int _bar;
public Fu(){
_bar = 12;
}
public void Square(){
_bar *= _bar;
}
}
(This is just an example by the way, I know this is the worst possible way of doing what I'm doing.)
Is there anyway that I could go:
Fu _fu = new Fu();
_fu.Square();
Console.WriteLine(_fu);
and _fu returns 144 instead of the class Fu? Or is that just a ridiculous question?
Regards, Harold
Edit: Console.WriteLine(_fu);
was a bad example. What if I wanted to do int twelveCubed = 12 * _fu
?
Console.WriteLine
has to convert the object to a string to print it; the default implementation uses the type's name, but you can override it:
public override string ToString() { return _bar.ToString(); }
or if (comment) you want a conversion operator:
public static implicit operator int(Fu fu) { return fu._bar; }
Add this method in your Fu class
public override string ToString()
{
return _bar.ToString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With