Windows Phone Developers

Tuesday, June 7, 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 = "Jackob Johnson";
            cls.Source = "Socchi";
            cls.Destination = "Moscow";
            cls.DOT = DateTime.Parse("12-Jan-2012");

            Console.WriteLine(cls.ToString());

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

No comments:

Post a Comment