Question: I have the below class, how do I print the list of objects in format [1,[2,3,8],[[]],10,[]] in C#?

```
public class InnerList
{
    private int val;
    private boolean isValue;
    private List<InnerList> intList;
}
public string ConvertToString()
{
    if (this.isValue)
    {
        return this.val + "";
    }
    else
    {
        return this.intList.ToString();
    }
}

```

In my caller, I will use something like below to print the list of objects in format [1,[2,3,8],[[]],10,[]]

```
System.out.println(list);

```

My question is how to achieve this in c#?

Answer: 
**[Solution:](https://dotnetfiddle.net/RTgXSU)**

```
public class InnerList
{
    //public only for simple initialization at usage example
    public int val;
    public bool isValue;
    public List<InnerList> intList;

    public override string ToString()
    {
        if (isValue)            
            return val.ToString();                
        return String.Format("[{0}]", intList == null ? "" : String.Join(", ", intList.Select(x => x.ToString())));
    }
}  

```

**Usage:**

```
var test = new InnerList
{
    intList = new List<InnerList>  {
        new InnerList { isValue = true, val = 1 },
        new InnerList { isValue = true, val = 2 },
        new InnerList
        {
            intList = new List<InnerList>  {
                new InnerList { isValue = true, val = 13 },
                new InnerList { isValue = true, val = 23 },
                new InnerList()
            }
        }
    }
};
Console.WriteLine(test);//[1, 2, [13, 23, []]]

```
It looks like you might run into the problem of circular them references here. Because an `InnerList` could reference its own parent in its `intList`. That is why I would recommend a serializer to do the job for you. It knows how to handle these circular references. I'm using `Newtonsoft.Json` here.

```
public override string ToString() 
{
    var settings = new JsonSerializerSettings();
    settings.PreserveReferencesHandling = PreserveReferencesHandling.All;
    return JsonConvert.SerializeObject(this, settings);
} 

```