Home > Mobile >  Why does my code return the type of the object instead of its value?
Why does my code return the type of the object instead of its value?

Time:04-09

I created a new class and used an operator in it

class blabla
{
    public static implicit operator blabla(int val)
    {
        return new blabla();
    }
}

class Program
{

    static void Main()
    {
        blabla x = 15;

        Console.WriteLine(x);

        Console.Read();
    }

}

But my program prints out ConsoleApplication1.blabla instead of 15. Why?

CodePudding user response:

You have created a conversion operator with this code:

public static implicit operator blabla(int val)
{
    return new blabla();
}

This code converts an int to a blabla but your code ignores val completely. You probably want to pass it to the new blabla instance.

Maybe you want something like this:

class blabla
{
    protected int val;
    public blabla(int val) {
        this.val = val;
    }
    public static implicit operator blabla(int val)
    {
        return new blabla(val);
    }
    public override string ToString() {
        return val.ToString();
    }
}

This calls the conversion operator and creates a new blabla with the passed in value.

Also, it overrides ToString() which is what gets called by Console.WriteLine. If you don't override that, you get the default - which is what you are seeing in your output.

However, this seems overly complicated. Why not delete the conversion operator and just call the constructor directly?

static void Main()
{
    blabla x = new blabla(15);
    Console.WriteLine(x);
    Console.Read();
}
  •  Tags:  
  • c#
  • Related