Nick
Nick

Reputation: 533

C# Iterate through nested properties using IEnumerator

I have seen examples (and official ones) for IEnumerator on lists and arrays or dicts, but I have a different problem. I have classes with properties, how may I implement the IEnumerable and IEnumerator in that case?

My properties classes are:

public class standardMessage
{
    public messageProperties message { get; set; }
    public messageFlag flag { get; set; }
}

public class messageProperties
{
    public string messageSubject { get; set; }
    public string messageBody { get; set; }
}

public class messageFlag
{
    public Boolean flagImportant { get; set; }
    public Boolean flagPersonal { get; set; }
}

And this is the Program:

public class Program
{
    static void Main(string[] args)
    {
        standardMessage myMessage = new standardMessage();

        myMessage.message = new messageProperties
        {
            messageSubject = "Greetings",
            messageBody = "Happy Weekend"
        };

        myMessage.flag = new messageFlag
        {
            flagImportant = false,
            flagPersonal = true
        };

        //how do I iterate through all properties, without knowing how many are there, instead of writing this worm line of code?
        Console.WriteLine(myMessage.message.messageSubject.ToString() + "\r\n" + myMessage.message.messageBody.ToString() + "\r\n" + myMessage.flag.flagImportant.ToString() + "\r\n" + myMessage.flag.flagPersonal.ToString());
        Console.ReadLine();
    }
}

Upvotes: 0

Views: 298

Answers (2)

Zakk Diaz
Zakk Diaz

Reputation: 1093

I made a very primitive object to json converter. I wouldn't use this in production and it's about 30% slower than Newtonsoft but it get's the job done.

private static string PrintObject(object obj, int depth = 1)
{
    var type = obj.GetType();
    if (type.IsPrimitive || type == typeof(Decimal) || type == typeof(String))
        return "\"" + obj.ToString() + "\"";
    var props = type.GetProperties();
    string ret = "";
    for (var i = 0; i < props.Length; i++)
    {
        var val = props[i].GetValue(obj);
        ret += new string('\t', depth) + "\"" + props[i].Name + "\":" + PrintObject(val, depth + 1);
        if (i != props.Length - 1)
            ret += "," + Environment.NewLine;
    }

    return ("{" + Environment.NewLine + ret + Environment.NewLine + new string('\t', depth - 1) + "}").Replace("\t", "  ");
}

Gives the result

{
  "message":{
    "messageSubject":"Greetings",
    "messageBody":"Happy Weekend"
  },
  "flag":{
    "flagImportant":"False",
    "flagPersonal":"True"
  }
}

Upvotes: 0

V0ldek
V0ldek

Reputation: 10603

If you want a production-grade way of printing your objects as a formatted string, you need to go and override ToString in all your classes to return whatever format you want.

However, if you just want to print the things on screen for debugging or logging purposes, why not JSON?

public static string ToJson(object @object) =>
    System.Text.Json.JsonSerializer.Serialize(@object, new JsonSerializerOptions{WriteIndented = true});
Console.WriteLine(ToJson(myMessage));

Prints

{
  "message": {
    "messageSubject": "Greetings",
    "messageBody": "Happy Weekend"
  },
  "flag": {
    "flagImportant": false,
    "flagPersonal": true
  }
}

Quick and dirty, but quick and working.

Upvotes: 1

Related Questions