Wednesday, June 19, 2013

Override ToString() method in c#

I hope all of you know what is overloading and overriding. If not please get few idea about that and then continue this post, because once you did not understand besic concept of overriding then you cannot follow it. Fine you are still reading means ,you know. Let’s go ahead.

As we know .NET class library is a huge collection of classes interface and all to provide in built mechanism to developer and basically I will say that this is the real power of .NET. As we know all class in .NET inherited from super class called “Object”. And this object class contains one method called ToString().

Which return string basically. Now question is “is it possible to override this method ?” –Answer is YES. We can .
And how ? It’s very simple to do that. Just use the override keyword in function definition like.

public override string ToString()
        {
            //return base.ToString();
            return "Hello World";
        }

Here when I will call ToString() method with the class object where it belongs to ,it will return me “Hello world” string rather than doing it’s routine work. See below code to get complete idea.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;

namespace BlogProject
{
    public class TestClass
    {
        public override string ToString()
        {
            //return base.ToString();
            return "Hello World";
        }
    }

    class Program
    {
        static void Main(string[] args)
         {
             TestClass obj = new TestClass();
             Console.Write(obj.ToString());
             Console.ReadKey();
         }
    }

}




No comments:

Post a Comment