Sunday, April 10, 2011

Overriding Tostring method

Problem
I created a list of person class but when run it through foreach loop and print it to console I was getting namespace.Person instead of actual person name.

Impact
Can't print the name of the person in the class.

Solution
I is a very common mistake that people make when they are new to OOP languages, well at least I did. I did't understand how we use console.writeln() method to print out integer or double values even though it accept only string value.

Ever wondered why when we create a custom class, we get few methods and properties even thought we did't even created them. Every class in C# is ultimately driven from object class. object class defines all these methods, one of them is ToString() method. To string is the method that gets called automatically when we use and print the value of an object. Following program shows how we could override and use to string method to help us out solving that small problem.


namespace ToStingExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person();
            Animal animal = new Animal("Dog");
            Vertex3D vertex3d = new Vertex3D(1,2,3);
            Console.WriteLine("Without overriding Tostring = {0}",person.ToString());
            Console.WriteLine("\nAfter Overridding Tostring method = {0}",animal.ToString());
            Console.WriteLine("\nAfter overridding and using Format method = {0}",vertex3d.ToString());
            Console.ReadLine();
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    public class Animal
    {
        public string Name { get; set; }

        public Animal(string name)
        {
            Name = name;
        }

        public override string ToString()
        {
            return Name;
        }
    }

    public class Vertex3D
    {
        public int X { get; set; }
        public int Y { get; set; }
        public int Z { get; set; }

        public Vertex3D(int x,int y, int z)
        {
            X = x;
            Y = y;
            Z = z;
        }

        public override string ToString()
        {
            return string.Format("{0},{1},{2}", X, Y, Z);
        }
    }

}


And here is the output that we get after running our little program.

1 comment:

  1. ToString is a method in object class can be overridden to change the implementation in any of the class which we declared.
    Dot Net Training in Chennai
    C# Training

    ReplyDelete