Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

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 219 views
1 answer 165 views
165 views asked Jan 13, 2017 by avibootz
2 answers 173 views
173 views asked Jan 13, 2017 by avibootz
...