4

i have class basically just a row of a table. this row contains many columns.

for testing purpose, i will need to output the reads i get .

so i need to output all of the columns in the row.

the class is like

    public class tableRow
    {
        public tableRow()
        {}
    public string id
    public string name
    public string reg
    public string data1
    ....
    ....
    ....
   <lot more columns>

}  

then i need to write like:

Console.WriteLine("id: " + tableRow.id);
Console.WriteLine("name: " + tableRow.name);
Console.WriteLine("reg: " + tableRow.reg);
Console.WriteLine("data1: " + tableRow.data1);
...
...
...
<lot more Console.WriteLine>

So i want to know , is there an easy way to get all of these output , without so much console.writeLine?

thanks

Benny Ae
  • 1,897
  • 7
  • 25
  • 37

5 Answers5

7

You can serialize tableRow into JSON and all columns will be printed. E.g. with JSON.NET (available from NuGet):

tableRow tr = new tableRow { id = "42", name = "Bob", reg = "Foo" };
Console.WriteLine(JsonConvert.SerializeObject(tr, Formatting.Indented));

Output:

{
  "id": "42",
  "name": "Bob",
  "reg": "Foo",
  "data1": null
}

I use this approach for logging (to show object state) - it's nice to have extension

public static string ToJson<T>(this T obj)
{ 
    return JsonConvert.SerializeObject(tr, Formatting.Indented);
}

Usage is simple:

Console.WriteLine(tr.ToJson());
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
2

This should work for classes as well as types with custom type descriptors:

private static void Dump(object o)
{
    if (o == null)
    {
        Console.WriteLine("<null>");
        return;
    }

    var type = o.GetType();
    var properties = TypeDescriptor.GetProperties(type);

    Console.Write('{');
    Console.Write(type.Name);

    if (properties.Count != 0)
    {
        Console.Write(' ');

        for (int i = 0, n = properties.Count; i < n; i++)
        {
            if (i != 0)
                Console.Write("; ");

            var property = properties[i];

            Console.Write(property.Name);
            Console.Write(" = ");
            Console.Write(property.GetValue(o));
        }
    }

    Console.WriteLine('}');
}

If you want to dump fields, and not properties, you can use type.GetFields() and make the necessary modifications to the above code. FieldInfo has a similar GetValue() method.

Note that this will not print "deep" representations of records. For that, you could adapt this into a recursive solution. You may also want to support collections/arrays, quote strings, and identify circular references.

Mike Strobel
  • 25,075
  • 57
  • 69
  • This only works with properties, the OP has fields. An easy fix (nice reflection base you have there), just something to note – James Nov 06 '13 at 22:12
  • They aren't proper field declarations, so I assumed he was just typing in shorthand. But yes, you are correct. – Mike Strobel Nov 06 '13 at 22:13
2

Here's a short example using reflection:

void Main()
{
    var myObj = new SomeClass();
    PrintProperties(myObj);

    myObj.test = "haha";
    PrintProperties(myObj);
}

private void PrintProperties(SomeClass myObj){
    foreach(var prop in myObj.GetType().GetProperties()){
     Console.WriteLine (prop.Name + ": " + prop.GetValue(myObj, null));
    }

    foreach(var field in myObj.GetType().GetFields()){
     Console.WriteLine (field.Name + ": " + field.GetValue(myObj));
    }
}

public class SomeClass {
 public string test {get; set; }
 public string test2 {get; set; }
 public int test3 {get;set;}
 public int test4;
}

Output:

test: 
test2: 
test3: 0
test4: 0

test: haha
test2: 
test3: 0
test4: 0
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
0

You could use reflection, to do it ... Give me a minute, I'll post some code

Something along:

PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public |
                                              BindingFlags.Static);
// sort properties by name
Array.Sort(propertyInfos,
        delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
        { return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });

// write property names
foreach (PropertyInfo propertyInfo in propertyInfos)
{
  Console.WriteLine(propertyInfo.Name);
}

You could add a check to see it's a string, and add some output as well, but that's the git of it.

Source from here

Noctis
  • 11,507
  • 3
  • 43
  • 82
  • 4
    If you don't yet have an answer to the question then you shouldn't be posting an answer. When you have an actual answer to the question *then* post an answer. Posting a non-answer just to get an earlier timestamp is not appropriate behavior. – Servy Nov 06 '13 at 22:06
0

if you set up an array of strings

var dataFields = new string[] { "id", "name", ...

you could do a foreach loop to populate the table, and reference the table data using the same array, allowing you to do another foreach loop to do the Console.WriteLine calls

If you wanted to, each table row could just be a dictionary, with the datafield as the key, and the data as a value. Then you can just loop though the dictionary