views:

397

answers:

4

Hi I have the Default aspx. I want to test overriding default methods like to ToString(). Whenever I use ToString(), I thought with following code it has to add "my text";? why not?

public partial class test : System.Web.UI.Page
{

    public override string ToString()
    {
        return base.ToString() + "my text"; 
    }


    protected void Page_Load(object sender, EventArgs e)
    {

        object test = 3333;
        Response.Write( test.ToString());
    }
}
+6  A: 

You want to call

this.ToString();

or simply

ToString();

What you did created an object with the name test, not the type test, and called the default ToString of object (well, of int, in this case).

Alternatively, if you want to create another page with the type test:

test newPage = new test();
test.ToString();
Kobi
Or delcare `test mypage = new test();`
NickLarsen
@Nick - I was just getting to that. Thanks.
Kobi
+1  A: 

The object test is not your class, it's just an object.

Unsliced
+5  A: 

As everyone said you are overriding the wrong method. If I understand correctly what you are trying to accomplish, then maybe an extension method is more appropriate :

public static class ObjectExtensions
{
    public static string ToCustomString(this object instance)
    {
        return instance.ToString() + "whatever";
    }
}

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        object test = 3333;
        Response.Write(test.ToCustomString());
    }
}
Diadistis
+1 because I think you understood what the OP is trying to do.
Kobi
Yes he did. So I see, it won't be possible to override the ToString() function of an object to use it with same Methodname in my class.
snarebold
It appears the problem is an incorrect understanding of virtual methods and what happens if you override them.
Thorarin
I wonder whether the OP thought that naming the class and the local variable the same (“test”) would matter.
Timwi
A: 

hello Snarebold

I would like you to rewrite your code in

protected void TestWrite(object sender, EventArgs e)
{
    test test = new test();

    System.Diagnostics.Trace.Write(test.ToString());
}

and then write

protected void TestWrite(object sender, EventArgs e)
{
    test test = new test();

    object testObject = test;

    System.Diagnostics.Trace.Write(testObject.ToString());
}

You will call ever the overwritten tostring method.

We call it "dynamic binding" in object oriented programming. Please be confident about this subject if you want to understand what really means an Object in computer science.

And... as Unsliced said :

"The object test is not your class, it's just an object."

Good Luck

Marcello Faga