Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to set what is returned when a variable is requested as is?

Tags:

c#

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?

like image 420
Harold Avatar asked Dec 22 '22 17:12

Harold


2 Answers

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; }
like image 178
Marc Gravell Avatar answered Dec 28 '22 23:12

Marc Gravell


Add this method in your Fu class

 public override string ToString()
 {
     return _bar.ToString();
 }
like image 30
scorpio Avatar answered Dec 29 '22 01:12

scorpio