Representing Objects as Strings


Representing an object as a string means different things depending on the object. The .NET framework provides a function called ToString by which you can turn any object into a string. Every object has a ToString function because ToString is a function in System.Object . Every class in .NET has System.Object as its root parent. If you write a class like Account and a programmer creates an object of type Account and calls ToString , by default the system prints the name of the class, which isn't very useful. However, you can override the default implementation of the ToString function to return something more meaningful, like the Account's balance for example. (For a full explanation of overriding methods see Chapter 5, "Class Inheritance.")

To implement your own ToString function:

  1. In a new line within your class type public override string ToString() .

  2. Type { .

  3. Type return "some string"; , where "some string" is the string representation of your objectyou can return either a literal value or a string variable.

  4. Type } ( Figure 4.64 ).

    Figure 4.64 Every class has a default ToString function. However, by default this function only outputs the class's name. To make it more useful you can override the default behavior as illustrated here.
     class CheckingAccount {    private string LastName = "Gates";    private string FirstName = "William";    private string AccountType =    "World Domination Free Checking";  public override string ToString()   {   string format =   "Name: {0} {1}<br> Account:{2}";   return string.Format(format,   LastName,FirstName,AccountType);   }  } 

graphics/tick.gif Tip

  • Some programmers provide more than one version of ToString in the class. The other versions have input parameters that enable the user of the class to specify a formatting string. Some examples of such classes are the Date class and the Decimal class ( Figure 4.65 ).

    Figure 4.65 The Date class and the Decimal class have different versions of ToString that enable you to pass format characters in order to get different representations of the variable's contents.
     DateTime dt = new DateTime(1999,12,25); string christmas =  dt.ToString("D");  Response.Write(christmas); //outputs: Saturday, December 25, 1999 Decimal balance = 1050.55M; string balinfo =  balance.ToString("C");  Response.Write(balinfo); //outputs: ,050.55 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net