Search code examples
c#output

dump data on C# like PHP


In PHP you can dump a variable data like:

<?php

$foo  = new stdClass();
$foo->prop1 = "ABC";
$foo->prop2 = 2024;

var_dump($foo);

output:

object(stdClass)#1 (2) {
  ["prop1"]=>
  string(3) "ABC"
  ["prop2"]=>
  int(2024)
}

How can I get similar data output in C# objects/classes?


Solution

  • This can be achieved in 2 ways basisc:

    Using Reflection: This approach leverages reflection to inspect the properties of an object and their values:

    using System;
    using System.Reflection;
    
    public class Program
    {
        public class MyClass
        {
            public string Prop1 { get; set; }
            public int Prop2 { get; set; }
        }
    
        public static void Main()
        {
            MyClass foo = new MyClass { Prop1 = "ABC", Prop2 = 2024 };
            var_dump(foo);
        }
    
        public static void var_dump(object obj)
        {
            Type type = obj.GetType();
            Console.WriteLine($"object({type.Name}) {{");
            
            foreach (PropertyInfo property in type.GetProperties())
            {
                var value = property.GetValue(obj);
                Console.WriteLine($"  [{property.Name}] => {value}");
            }
            
            Console.WriteLine("}");
        }
    }
    

    output:

    object(MyClass) {
      [Prop1] => ABC
      [Prop2] => 2024
    }
    

    Using ToString Override: For more control, you can override the ToString method in your class to provide custom string representation:

    using System;
    
    public class Program
    {
        public class MyClass
        {
            public string Prop1 { get; set; }
            public int Prop2 { get; set; }
    
            public override string ToString()
            {
                return $"object(MyClass) {{\n  [Prop1] => {Prop1}\n  [Prop2] => {Prop2}\n}}";
            }
        }
    
        public static void Main()
        {
            MyClass foo = new MyClass { Prop1 = "ABC", Prop2 = 2024 };
            Console.WriteLine(foo.ToString());
        }
    }
    

    output:

    object(MyClass) {
      [Prop1] => ABC
      [Prop2] => 2024
    }
    

    I hope this is useful to the community, greetings.