Friday, December 29, 2023

ToString method in Object class

In .Net, all the data types are derived from Object data type. Object data type has a method named ToString, which is overridable and provides a basic implementation of converting any object to String.

By default ToString returns the objects Class name along with its namespace.

Example:

namespace HelloWorld;
class Employee {
}
class Program
{
  static void Main(string[] args)
  {
    var emp = new Employee();
    Console.WriteLine(emp.ToString());
  }
}

Output:

HelloWorld.Employee

As all the numbers are derived from Object data type and ToString is overridable, .net has a overridden implementation of ToString for Numbers, which converts them to String.

var a = 123;
Console.WriteLine(a);

Output:

123

No comments:

Post a Comment

Object Oriented Programming- 2- Inheritance

Inheritance is one of the fundamental attributes of object-oriented programming. It allows you to define a child class...