Public
Authored by Simon Schwitz

C# DataClass Extension

Read my Blog-Post for more details!

DataClass

This Class overrides the default ToString() Method of C# by letting the child extend DataClass.
It can translate all simple types (int, string, ...) and types including ICollection (arrays, lists, dictionaries, ...) to strings.

Tested with .NET Core 2.0

public class SampleData : DataClass     
{     
    // code here     
}

Sample Class

public class SampleData : DataClass
{
    internal static byte[] data
    {
        get
        {
            var buff = new byte[32];
            new Random().NextBytes(buff);
            return buff;
        }
    }

    private object[] array;
    public Dictionary<object, object> dict;
    public object[] Array { get; set; }
    private Dictionary<object, object> Dict;

    public SampleData()
    {
        // generate random instance
        var rdm = new Random();
        var arrSize = rdm.Next(1, rdm.Next(1, 50));

        // init array and dictionary
        array = new object[arrSize];
        dict = new Dictionary<object, object>();

        // fill array and dictionary with random data
        for (var i = 0; i < arrSize; i++)
        {
            var x = rdm.Next();
            array[i] = RdmVal(x, rdm);
            dict.Add(array[i], RdmVal(x, rdm));
        }

        // set property to the same value as the field for showcase purposes
        Array = array;
        Dict = dict;
    }

    //---------------------------------------

    // helper function to generate random values
    private object RdmVal(int seed, Random rdm = null)
    {
        if (rdm == null) rdm = new Random();
        return seed % 2 == 0 ? (object)rdm.Next() : Guid.NewGuid().ToString().Replace("-", "");
    }
}

Console Output

Output is formatted here

SampleData(
    data=[97, 242, 102, 253, 143, 138, 58, 138, 201, 93, 99, 120, 207, 162, 95, 72], 
    Array=[94734e04fd314d3ba38e32467b2d59f3, 1d89dfaf9ab14adbab1fa55e9b52ffe9], 
    Dict=[[94734e04fd314d3ba38e32467b2d59f3, eba67587e1ef43ffa4b11711f0fc8533], [1d89dfaf9ab14adbab1fa55e9b52ffe9, 640ef2934bb4417ab8f23bc86575ab3f]], 
    array=[94734e04fd314d3ba38e32467b2d59f3, 1d89dfaf9ab14adbab1fa55e9b52ffe9], 
    dict=[[94734e04fd314d3ba38e32467b2d59f3, eba67587e1ef43ffa4b11711f0fc8533], [1d89dfaf9ab14adbab1fa55e9b52ffe9, 640ef2934bb4417ab8f23bc86575ab3f]], dec=79228162514264337593543950335
)
Edited
DataClass.cs 1.4 KB
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment