Advertisement
Method | Description |
---|---|
String ToString() | This method returns a String representation of the invoked object. |
//C# Example of ToString() method
using System;
class A
{
public static void Main()
{
//Creating a String object
A ob = new A();
// Printing the object, which implicitly calls the ToString() method
//Which will print fully qualified name of the object type
Console.WriteLine(ob);
}
}
A
Advertisement
//C# Overriding the ToString() method
using System;
class A
{
//Overriding the ToString() method
public override String ToString()
{
return "We have created an object";
}
//Defining the Main() method
public static void Main()
{
//Creating two objects of class A
A ob1 = new A();
A ob2 = new A();
//Printing two objects of class A
Console.WriteLine(ob1);
Console.WriteLine(ob2);
}
}
We have created an object
We have created an object
//C# Overriding the ToString() method to give a specific String message for each object, when it is printed.
using System;
class Database
{
//Instance variables
String name;
String city;
int age;
float donation;
//Defining the PutName() method
public void PutName(String str)
{
name = str;
}
//Defining the PutCity() method
public void PutCity(String str)
{
city = str;
}
//Defining the PutName() method
public void PutAge(int i)
{
age = i;
}
//Defining the PutDonation() method
public void PutDonation(float f)
{
donation = f;
}
//Overriding the ToString() method
public override String ToString()
{
return name + " from " + city + " aged " + age + " has donated - " + donation + "$";
}
//Defining the Main() method
public static void Main()
{
//Creating the first object
Database ob1 = new Database();
ob1.PutName("Howard");
ob1.PutCity("New York");
ob1.PutAge(40);
ob1.PutDonation(1000.50f);
//Printing the first object
Console.WriteLine(ob1);
//Creating the second object
Database ob2 = new Database();
ob2.PutName("Steve");
ob2.PutCity("Sydney");
ob2.PutAge(30);
ob2.PutDonation(500.50f);
//Printing the second object
Console.WriteLine(ob2);
}
}
Howard from New York aged 40 has donated - 1000.5$
Steve from Sydney aged 30 has donated - 500.5$
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement