1

For example, if I have a class that creates the following method:

public new string ToString() {
//some code
}

But let's say that I needed to call the ToString method from the Object class. How would I do that?

1
  • 1
    can you explain more, whats your problem?
    – Alex
    Sep 6, 2012 at 15:10

2 Answers 2

4

You should cast to the Object and then call the method:

class A
{
    public new string ToString()
    {
        return "bugaga!";
    }
}

static void Main(string[] args)
{
    var a = new A();

    Console.WriteLine(a.ToString());
    Console.WriteLine(a); // here object 'a' will be casted to object
}

output:

bugaga!
ConsoleApplication4.Program+A
1

Use ((Object)myvariable).ToString(), casting back to the base.

More here:

http://msdn.microsoft.com/en-us/library/6fawty39(v=vs.100).aspx

Are you sure you really want to create a new ToString() on your class though? It's common to override the original implementation instead:

http://msdn.microsoft.com/en-us/library/ms173154(v=vs.100).aspx

1
  • I would bet this is a sanitized example. Sep 6, 2012 at 15:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.