How to override the ToString() method in C#

2 Answers

0 votes
using System;
 
namespace ConsoleApplication_C_Sharp
{
    class MyClass
    {
    }
 
    class MyClassWithOverride {
        public override string ToString() {
            return "my override ToString()";
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyClass myclass = new MyClass();
            MyClassWithOverride myclasswithoverride = new MyClassWithOverride();
 
            Console.WriteLine(myclass);
            Console.WriteLine(myclasswithoverride);
        }
    }
}
 
 
/*
run:
     
ConsoleApplication_C_Sharp.MyClass
my override ToString()
 
*/

 



answered Apr 25, 2017 by avibootz
edited Sep 13, 2020 by avibootz
0 votes
using System;

class Test {
    int _a;
    int _b;

    public Test(int a, int b) {
        _a = a;
        _b = b;
    }

    public override string ToString() {
        return string.Format("ToString(): {0}, {1}", _a, _b);
    }
}

class Program
{
    static void Main()
    {
        Test o = new Test(9, 5);
        
        Console.WriteLine(o);
    }
}

 
 
/*
run:
     
ToString(): 9, 5
 
*/

 



answered Sep 13, 2020 by avibootz

Related questions

1 answer 253 views
1 answer 180 views
180 views asked Jan 13, 2017 by avibootz
2 answers 183 views
183 views asked Jan 13, 2017 by avibootz
...