Overriding ToString Method has its own advantages.
For example, the following class has four fields
public class ClassExec { string _Name; public string Name { get { return _Name; } set { _Name = value ;} } public string Source { get; set; } public string Destination { get; set; } public DateTime DOT { get; set; }
If you try to use the ClassExec.ToString() method it will return the fully qualified Class name as default. This doesn't help us much.
Instead let us override the ToString method to return the four fields in a formatted way
public override string ToString() { return (Name + ' ' + Source + ' ' + Destination + ' ' + DOT); }
The following code will now produce the desired output:
ClassExec cls = new ClassExec(); cls.Name = "Jackob Johnson"; cls.Source = "Socchi"; cls.Destination = "Moscow"; cls.DOT = DateTime.Parse("12-Jan-2012"); Console.WriteLine(cls.ToString());
No comments:
Post a Comment