Override ToString() implementation of anonymous objects

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.


As far as im aware, there is no way to override the default ToString behaviour.
Might be worthwhile looking at some of the posts from Eric Lippert about anonymous types: http://blogs.msdn.com/b/ericlippert/archive/tags/anonymous+types/

Probably best to create a simple class for this purpose:

e.g.

public class MyClass
{
  public DateTime Time { get; set; }
  public string Name { get; set; }

  public override string ToString()
  {
    return string.Format("Time = {0}. Name = {1}.", Time, Name);
  }
}

Tags:

C#