ToString() Operator Overloading is laso possible in C#. You just have to wite a override ToString() method to add extra/Different functionality. The ToString() override method exapmle is given below, where it write an addition line on console as well as it passes a constant string back to writeline method.
Please note that ToString method get called twice in this example. Because the first writeline statement automatically call this override method.
Console.WriteLine(a1);
In case you feel any difficulty while implementing this. Please comment.
Tostring() Operator Overloading in C# Example:
using System;
using System.Collections.Generic;
using System.Text;
namespace Console_App
{
public class Class1
{
public static void Main()
{
Class2 a1 = new Class2(10);
Console.WriteLine(a1);
Console.WriteLine();
Console.WriteLine(a1.ToString());
Console.ReadLine();
}
}
public class Class2
{
public int i;
public Class2(int j)
{
i = j;
}
public override string ToString()
{
Console.WriteLine("ToString() Method Get Called. ");
return "ToString() Operator OverLoading. ";
}
}
}
No comments:
Post a Comment