Search code examples
c#java.nettranslationequivalent

Translate code from Java to .NET


I need to translate this fragment from Java to .NET (rather C#, but I know Visual Basic too). This is code:

typeStrings = new Dictionary<Int16, String>();

    Field[] fields = Type.class.getDeclaredFields();

    for (Field field : fields) {
        try {
            typeStrings.put(field.getInt(null), field.getName());
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }           
    }

First line (Dictionary class) is from .NET (my translation try ;)). I know the Field class is from java.lang.reflect.Field, but I couldn't found .NET equivalent. Kind regards!


Solution

  • var typeStrings = new Dictionary<int, string>();
    
    FieldInfo[] fields = yourObject.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
    foreach (var field in fields)
    {
        typeStrings.Add((int)field.GetValue(yourObject), field.Name);
    }