Question

Imagine the following example:

class foobar
{
    string b = string.Empty;
    public foobar(string abc)
    {
        b = abc;    
    }
    public override string ToString()
    {
        return b;
    }
}

I could use it like this:

void Main()
{
    foobar test = new foobar("test string");
    Console.WriteLine(test);
}

With the expected output of test string

What if I do something like this?

void Main()
{
    object test2 = (object)new foobar("test string 2");
    Console.WriteLine (test2);
}

I still get the output test string 2 even though I boxed my class inside object.

It even works when I use an object returned by a method:

private object DoSomething()
{
    return (object) new foobar("test3..");
}

How does the CLR know which type my object is was and where to look for the .ToString() implementation?

Does this even work when used accross assembly boundaries?

Was it helpful?

Solution

ToString() is visible on and accessible via Object.

Providing an overridden implementation of a method and having it called when the object is accessed as its ancestor or a base class is a core requirement and benefit of polymorphism.

Specifying an override tells the object's metadata to remap calls to the ancestor's ToString() method to the new one, even if that object is accessed as though it were its ancestor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top