May 17, 2016
ToString() Method Overriding in C# with Example
In dotnet, every type directly or directly inherit from Object class. Object class contains some methods like ToString(), GetHashCode(), Equals(), etc and all of these methods are available to all the derived classes. As the name suggests, ToString() works fine with the built in types but in case of complex types, it does not work as expected. To fix this issue, we need to override this method so that we can get the desired output. Example of ToString() override is given below.
using System; namespace Hello_World { class Program { static void Main(string[] args) { Student std = new Student(); std.FirstName = "Mark"; std.LastName = "Albert"; Console.WriteLine(std.ToString()); } } class Student { public string FirstName { get; set; } public string LastName { get; set; } public override string ToString() { return FirstName + " " + LastName; } } }