Wrox Programmer Forums
Go Back   Wrox Programmer Forums > C# and C > C# 2008 > C# 2008 aka C# 3.0
|
C# 2008 aka C# 3.0 Discuss the Visual C# 2008 (aka C# 3.0) language
Welcome to the p2p.wrox.com Forums.

You are currently viewing the C# 2008 aka C# 3.0 section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old November 10th, 2008, 06:37 PM
Friend of Wrox
 
Join Date: Sep 2007
Posts: 169
Thanks: 7
Thanked 2 Times in 2 Posts
Default Why would you override ToString()?

Hi

I never done tried to do this before but I seen people override the ToString() method and I really don't why you would override it.

I thought the ToString() method was used to convert something into a string so why would you override this to change the formatting?

Also if you say have this override in a class(say class A) and you then say had this

int num = 10;
string hold = num.ToString();

would this take the overridden string or just the regular string? I also home it does not effect other class that use the ToString() method.

I just don't see a point why not just make another method with a different name and put the formatting in there?

Thanks

 
Old November 11th, 2008, 01:29 AM
Friend of Wrox
 
Join Date: Sep 2005
Posts: 812
Thanks: 1
Thanked 53 Times in 49 Posts
Default

Hi

Say you have a class called Coordinates which has both X, Y and Z axis, you can use the ToString Override to display all the axis in a particular format (Mostly when you mention coordinates - you take all the axis into consideration right)

like (X,Y,Z).

Coordinates CD = New Coordinates(12,23,20)
Console.Writeline (CD.ToString)

Output will be (12,23,20)

The same can be taken for any class

Cheers
Shasur

C# Code Snippets (http://www.dotnetdud.blogspot.com)

VBA Tips & Tricks (http://www.vbadud.blogspot.com)
 
Old November 11th, 2008, 01:45 AM
Friend of Wrox
 
Join Date: Sep 2007
Posts: 169
Thanks: 7
Thanked 2 Times in 2 Posts
Default

I still don't get it could you not just make a method that has the correct format and not override the toString?

what happens if you got to convert something just to a string? You won't be able to use the toString method anymore. To me it seems like your limiting yourself.

So I am just trying to see the logic behind it.

 
Old November 11th, 2008, 02:25 AM
Friend of Wrox
 
Join Date: Sep 2005
Posts: 812
Thanks: 1
Thanked 53 Times in 49 Posts
Default

Hi

You are overriding 'ToString' for that particular class and you will still be able to use ToString method as usual

That is

int num = 10;
string hold = num.ToString();

and

Coordinates CD = New Coordinates(12,23,20)
Console.Writeline (CD.ToString) ' Overridden in Coordinates class

will co-exist

Cheers
Shasur


C# Code Snippets (http://www.dotnetdud.blogspot.com)

VBA Tips & Tricks (http://www.vbadud.blogspot.com)
 
Old November 11th, 2008, 03:20 AM
Friend of Wrox
 
Join Date: Sep 2007
Posts: 169
Thanks: 7
Thanked 2 Times in 2 Posts
Default

This is is in the same class right?

I also notice you have ToString and not ToString() is that just a typo?

But everything that is getting referenced by the new Object will have the new format of that ToString();

So I just want to clarify if say have overwritten the ToString() method in the Coordinates class and in this same class you do


int num = 10;
string hold = num.ToString();

it will just convert the number to a string?

So the overriding of the string only happens on newly created objects?

I still have not recived an answer to why you would want to override the String vs just make a new method with a new name.

To me if I saw this

int num = 10;
string hold = num.ToString();

and

Coordinates CD = New Coordinates(12,23,20)
Console.Writeline (CD.ToString) ' Overridden in Coordinates class

it would not be self evident that the CD.ToString() is the overridden string.

I would find it kinda a weird why you would be trying to convert the object to a string and then printing it out so I probably would investigate further but to me it would be just be simpler to have CD.newStringFormat() or something like that.

 
Old November 11th, 2008, 04:16 AM
Friend of Wrox
 
Join Date: Jun 2008
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts
Default

int num = 10;
string hold = num.ToString();
it will just convert the number to a string?


Yes, of course. You did *NOT* override the method ToString for INT, you only overrode it for Coordinates.

Coordinates CD = New Coordinates(12,23,20)
Console.Writeline( CD.ToString ) ' VB allows you to omit the parens

it would not be self evident that the CD.ToString() is the overridden string.


Well, maybe not self evident to you, but sure would be self-evident to me and to Shasur. It's the only possible meaning. I see
    CD.ToString
and I *know* that the ToString is a method on the class that CD is an instance of. (Okay, technically it could be a method on a superclass, but that's the same thing.)

I honestly don't see how you could take it to mean anything else.

Incidentally, if I *do* have a class like this:
Code:
Public Class Coordinate 
    private x As Double
    private y As Double
    private z As Double

    public Sub New( cx As Double, cy As Double, cz As Double )
        me.x = cx
        me.y = cy
        me.z = cz
    End Sub

    public Overrides Function ToString( ) As String
        return "(" & x & "," & y & "," & z & ")"
    End Function
End Class
And then once that is in place, I can do
    Dim CD As New Coordinates( 7.5, 22, 12.3333 )
and then *EITHER*
    Console.WriteLine( CD.ToString() )
*OR* just
    Console.WriteLine( CD )
because of course WriteLine invokes the ToString() method by default in order to get a string to write.
 
Old November 11th, 2008, 04:22 AM
samjudson's Avatar
Friend of Wrox
 
Join Date: Aug 2007
Posts: 2,128
Thanks: 1
Thanked 189 Times in 188 Posts
Default

By default ToString() outputs the name of the class (this is actually implemented by Object.ToString())

MyClass c = new MyClass();
Console.WriteLine(c.ToString()); // outputs "MyNamespace.MyClass";

Every instance where ToString prints out something other than the class name (including Int32.ToString) is an instance of ToString being overridden. That is what its there for.

So I would always override ToString() if I wanted to convert a class I had written to a string.

/- Sam Judson : Wrox Technical Editor -/
 
Old November 11th, 2008, 06:01 AM
Friend of Wrox
 
Join Date: Jun 2008
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts
Default

And even if there's no real-world purpose in creating the ToString for a given class (e.g, some class used for displaying database query results to a browser, perhaps--you'd clearly almost never use ToString for that display), I would still create the ToString for debugging purposes, more often than not. Even if I only used the method while debugging, it could be a *LOT* more convenient than looking around in the dump of an object for the relevant data members.
 
Old November 11th, 2008, 06:56 AM
Friend of Wrox
 
Join Date: Jun 2003
Posts: 1,093
Thanks: 1
Thanked 12 Times in 11 Posts
Default

The .NET Framework types override ToString() all the time for a varierty of purposes. Here's the System.Int32.ToString() override:

public override string ToString()
{
    return Number.FormatInt32(this, null, NumberFormatInfo.CurrentInfo);
}

On my computer, this creates a string consisting of a negative sign if the value is negative, and a sequence of digits ranging from 0 to 9 with no leading zeroes. All the primitive types override ToString() to define how numeric values are formatted and displayed, depending on the calling threads current culture.

Or think of how useless System.Text.StringBuilder.ToString() would be if it didn't override ToString(), and just returned the name of the StringBuilder instance. Here's its ToString() override:

public override string ToString()
{
    string stringValue = this.m_StringValue;
    if (this.m_currentThread != Thread.InternalGetCurrentThread())
    {
        return string.InternalCopy(stringValue);
    }
    if ((2 * stringValue.Length) < stringValue.ArrayLength)
    {
        return string.InternalCopy(stringValue);
    }
    stringValue.ClearPostNullChar();
    this.m_currentThread = IntPtr.Zero;
    return stringValue;
}

This enables a StringBuilder to display a string representationn of its state, not just its name.

And that's the key point: System.Object provides a ToString() method to give all types a way to obtain a reasonable representation of their current value.

Another good example of this would be something like System.Collections.Generic.KeyValuePair<TKey, TValue> which actually uses a StringBuilder in its implementation of ToString():

public override string ToString()
{
    StringBuilder builder = new StringBuilder();
    builder.Append('[');
    if (this.Key != null)
    {
        builder.Append(this.Key.ToString());
    }
    builder.Append(", ");
    if (this.Value != null)
    {
        builder.Append(this.Value.ToString());
    }
    builder.Append(']');
    return builder.ToString();
}





 
Old November 11th, 2008, 10:41 AM
Friend of Wrox
 
Join Date: Sep 2008
Posts: 234
Thanks: 0
Thanked 32 Times in 30 Posts
Default

Old Pedant raises a good case for creating a custom ToString() for debugging purposes. A "pure" class (not a form) should never do any graphical user interface calls directly. You would only do that for debugging purposes and ToString() is a common place to do it. For example, if your class has members named firstName, middleInitial, and lastName, you could override ToString() to build a string of all three string values and examine them in a single place with a single breakpoint.

Also keep in mind that overriding a method actually replaces it with your own version of it, while altering the signature of the method (e.g., changing its parameter list) means you can use the same method name but call different versions of the method.

Dr. Purdum

Jack Purdum, Ph.D.
Author: Beginning C# 3.0: Introduction to Object Oriented Programming (and 14 other programming texts)





Similar Threads
Thread Thread Starter Forum Replies Last Post
toString() praveena Java Basics 3 March 20th, 2006 10:52 PM
Request.UrlReferrer.ToString() mike72 BOOK: ASP.NET Website Programming Problem-Design-Solution 2 September 5th, 2005 09:31 AM
Problem with Request.UrlReferrer.ToString velateam .NET Framework 2.0 0 April 5th, 2005 08:22 AM
enum toString() overloading kramis8 C# 0 November 21st, 2004 07:55 PM
.ToString() functions cuts off zeros olambe BOOK: ASP.NET Website Programming Problem-Design-Solution 2 July 6th, 2004 10:20 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.