2.10 String Representation of Objects

 <  Day Day Up  >  

When creating a new class, you want to add the ability to return a readable string that represents your object.


Technique

Create an overridden method named ToString that returns a string data type, as shown in Listing 2.8.

Listing 2.8 Overriding the ToString Method to Associate Your Class with a Human-Readable String
 using System; namespace _10_ObjectString {     public class MediaDevice     {         public override string ToString()         {             return "a generic media device";         }     }     public class Television : MediaDevice     {         public override string ToString()         {             return "a Television";         }     }     class Class1     {         [STAThread]      static void Main(string[] args)      {          Television tv = new Television();             MediaDevice md = new MediaDevice();             MediaDevice mdtv = (MediaDevice) new Television();             Console.WriteLine( "tv is {0}\nmd is {1}\nmdtv is {2}", tv.ToString(),                 md.ToString(), mdtv.ToString() );         }     } } 

Comments

Every class that you create in Visual C# .NET is transparently derived from the System.Object class, regardless of any other base class you derive from. The class inherits the method from the Object class. ToString is a method in the System.Object class used to return a human-readable string that represents whatever object the method is called on. For instance, within the Int32 class, which is a class that represents a 32-bit integer, the ToString method converts the internal integer member variable to a string and returns that conversion result. It is up to you to determine how you want to define the ToString method for your class. If you do not override this method, the default method simply returns the namespace-qualified name of the class.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

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