Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override ToString() implementation of anonymous objects

Tags:

c#

        var sample = new
        {
            Time = DateTime.Now,
            Name = "Hello"
        };
        Trace.TraceInformation("{0}", sample);

outputs as

ProcessInvocation86.exe Information: 0 : { Time = 04.11.2012 22:07:52, Name = Hello }

I'd like different formatting in my application. Is there a way to change the implementation of ToString() for anonymous objects in C#? Maybe some static field per AppDomain or something?

like image 981
UserControl Avatar asked Nov 04 '12 20:11

UserControl


People also ask

Can we override toString method?

We can override the toString() method in our class to print proper output. For example, in the following code toString() is overridden to print the “Real + i Imag” form.

Why do we override toString method in Java?

Override the toString() method in a Java Class A string representation of an object can be obtained using the toString() method in Java. This method is overridden so that the object values can be returned.

Why is it a good idea to override the toString and equals methods when creating a new class?

There will be no information about state or properties of an object. Therefore, it is recommended that every class you write must override toString() method so that you quickly get an overview of an object. You must override toString() method in such a way that it should provide enough information about an object.


1 Answers

No, you can't do this - ToString, Equals, and GetHashCode have default implementation provided by framework. To override this functionality you should inherit from your anonymous type, which is impossible.

Use String.Format to get desired output.

like image 113
Sergey Berezovskiy Avatar answered Sep 20 '22 22:09

Sergey Berezovskiy