In this post, you will see what does ToString() method do in a class and why do developers override this method in classes. The ToString() belongs to Object class which is super type of all classes. So, ToString() is available to all classes with its default implementation. Look at the following example in this regard.
Example1class Animal
{
public string Name { get; set; } = string.Empty;
public override string ToString()
{
// using object base class implementation
return base.ToString() ?? "The object is null.";
}
}
class Program
{
static void Main()
{
Animal a1 = new Animal { Name = "Cat" };
Animal a2 = new Animal { Name = "Dog" };
Console.WriteLine(a1.ToString());
Console.WriteLine(a2.ToString());
}
}
The Animal class uses the default implementation of ToString(). The developer has not provided any custom implementation. When you run the code, you get name of class for each instance of Animal class. This is not valuable information about different objects of class.
The output is:
Animal
Animal
To provide useful information about each instance of class (Animal here), developer must override ToString() method in meaningful way. This is illustrated in the following example.
Example2class Animal
{
public string Name { get; set; } = string.Empty;
public override string ToString()
{
// using custom implementation
return "The name of animal is " + this.Name;
}
}
class Program
{
static void Main()
{
Animal a1 = new Animal { Name = "Cat" };
Animal a2 = new Animal { Name = "Dog" };
Console.WriteLine(a1.ToString());
Console.WriteLine(a2.ToString());
}
}
The output is:The name of animal is Cat
The name of animal is Dog
You can include more than one field or property for information of object. This is demonstrated in the following example.
Example3
class Animal
{
public string Name { get; set; } = string.Empty;
public int Age { get; set; }
public override string ToString()
{
return "The name of animal is " + this.Name + " and age is " + this.Age + ".";
}
}
class Program
{
static void Main()
{
Animal a1 = new Animal { Name = "Cat", Age = 2 };
Animal a2 = new Animal { Name = "Dog", Age = 4 };
Console.WriteLine(a1.ToString());
Console.WriteLine(a2.ToString());
}
}
The output is: The name of animal is Cat and age is 2.
The name of animal is Dog and age is 4.
No comments:
Post a Comment