Like it

Sunday, July 10, 2011

How to Override ToString Method in C# (VB.NET)

Customize ToString Method in C# (VB.NET)

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 = "Nadir"; 
cls.Source = "Only-dotnet"; 
cls.Destination = "Sydney"; 
cls.DOT = DateTime.Parse("12-Jan-2012"); 
Console.WriteLine(cls.ToString());



No comments:

Post a Comment