cllpse
cllpse

Reputation: 21727

IEnumerable of Custom class and String.Join()

I've created a class which acts as an all-purpose DataType class. I am doing this because I need to serialize a collection of misc-typed objects to JSON, and I'd like to be able to create the full data set as a collection. Like so:

JSON.Serialize(new []
{
    new Chameleon("aDate", DateTime.Now),
    new Chameleon("aString", "FUBAR")
});

The following is a simplified version of my implementation:

class Chameleon
{
    private String _type;
    private String _key;
    private Object _value;

    public Chameleon(String key, String value)
    {
        _type = "string";
        _key = key;
        _value = value;
    }

    public Chameleon(String key, DateTime value)
    {
        _type = "string";
        _key = key;
        _value = value;
    }

    public new String ToString()
    {
        // returns internal data, formatted data according to _type
    }
}

This is all well and good, but when I try and join - or concatinate if you will - a collection of Chameleon using String.Join(), ToString() on Chameleon objects in the collection are not called by the String.Join() method; instead I get the usual namespace + class-name string returned.

Why is String.Join() not calling my custom ToString() implementation? What am I missing?


Here's what I'm doing:

JSON.Serialize(String.Join<Chameleon>(",", new []
{
    new Chameleon("aDate", DateTime.Now),
    new Chameleon("aString", "FUBAR")
}));

Upvotes: 1

Views: 575

Answers (3)

wageoghe
wageoghe

Reputation: 27608

That was it. Try defining your ToString like this:

  public override String ToString() //Note the override rather than new
  {
    //Format your string etc.
  }

Upvotes: 2

Tomas Jansson
Tomas Jansson

Reputation: 23472

You need to put ToString on each Chameleon object otherwise you have an array of Chameleon object instead of an array of string which should be used.

Upvotes: 0

Drew Noakes
Drew Noakes

Reputation: 311007

My guess is that this occurs because you define ToString as a new method, rather than overriding it. Try this code instead:

public override String ToString()
{
    // returns internal data, formatted data according to _type
}

Upvotes: 3

Related Questions