C# - work with a struct type - enumerate and count

By , 9/17/2012
(1 ratings)
My example call returns:
sMyStruct = "iId;sValue;oTag"
iCount = 3

Author: Krzysztof, translation by Michael List
Translate to VB
public struct MyStruct
{
    public int iId;
    public string sValue;
    public object oTag;
}

void example()
{
    //---------------------
    // it can look like this

    MyStruct oStructure = new MyStruct();
    oStructure.iId = 1;
    oStructure.sValue = "Test";
    StructClass oStructCls = new StructClass();
    string sMyStruct = oStructCls.ToCsvList((object)oStructure);
    int iCount = oStructCls.Count((object)oStructure);

    //---------------------------------------
}

class StructClass
{

    // Count of elements in a struct
    public int Count(object oStruct)
    {
        int iCount = 0;
        System.Type oType = oStruct.GetType();
        foreach (FieldInfo oFi in oType.GetFields())
        {
            iCount++;
        }
        return iCount;
    }

    public string ToCsvList(object oStruct)
    {
        string sCsv = "";
        System.Type oType = oStruct.GetType();
        foreach (FieldInfo oFi in oType.GetFields())
        {
            sCsv += ";" + oFi.Name;
            System.Type feldTyp = oFi.FieldType;  //e.g.:  System.string
        }
        sCsv = sCsv.Substring(1);
        return sCsv;
    }
}

Comments

 

Log in, to comment!