1

I am new to c# and I am trying to print a user defined structure. Code:

        var tracksArr = new[]
        {new
            {   vessel = GetVesselInfo(aisRecord.VesselId),
                points = new[]
                {   new
                    {   stampUtc = aisRecord.Time.ToString("yyyy-MM-ddTHH:mm:ssZ"),
        }}}}
   
        foreach (var item in tracksArr)
            {Console.WriteLine("qqq: " + item.ToString());}

which prints:

qqq: { vessel = { key = 123456,0, mmsi = 7891011, imo = 0 }, points = 
<>f__AnonymousType18`6[System.String,System.Double,System.Double...

what is this mysterious <>f__AnonymousType18 and how do I get the value of points?

2
  • As an aside, I'd strongly recommend that you get Visual Studio to format your code in the default style before posting on Stack Overflow. While it's fine for you to have personal preferences around where braces go etc, it makes it harder for everyone else to read if it's very different from the defaults which are very widely used. Commented Jun 24, 2020 at 11:59
  • Thanks John, was trying to minimize space here. Commented Jun 24, 2020 at 12:36

1 Answer 1

2

For each anonymous type with unique set of fields (the new { ... } statements in means creation of instance of anonymous type) compiler will generate a class, which name will look like <>f__AnonymousType18. This class has overridden ToString method, but arrays/collections - don't and point is an array, so by default ToString returns type name which is YourAnonymousTypeName[] for arrays. You can use string.Join to output your collection:

Console.WriteLine($"qqq: {{vessel = {item.vessel}, points = {string.Join(", ", item.points.Select(p => p.ToString()))}}}");

Or create/use another collection type for points which will have overridden ToString method which returns string with all elements:

public static class ext
{ 
    public static MyList<T> ToMyList<T>(this T[] arr)
    {
        return new MyList<T>(arr);
    }
}
public class MyList<T> : List<T>
{
    public MyList(T[] arr)
    {
        AddRange(arr);
    }
    
    public override string ToString()
    {
        return string.Join(",", this);
    }
}

var tracksArr = new[]
       {new
            {   vessel = 1,
                points = new[]
                {   new
                    {   stampUtc = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ"),               }
                }
                .ToMyList()
            }               
        }; // prints "qqq: { vessel = 1, points = { stampUtc = 2020-06-24T14:58:08Z } }"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.