Take the 2-minute tour ×

I was wondering if its possible to parse strings to defined values for uint. Something similar to http://msdn.microsoft.com/en-us/library/essfb559.aspx. So if I have the following declarations:

public const uint COMPONENT1 = START_OF_COMPONENT_RANGE + 1;
public const uint COMPONENT2 = START_OF_COMPONENT_RANGE + 2;
public const uint COMPONENT3 = START_OF_COMPONENT_RANGE + 3;

And have an xml file defined the following way:

<node name="node1" port="12345">

I want to be able to parse the string COMPONENT1 to the uint value of COMPONENT1. This to have easier overview of the xml file instead of the numbers 5001, 5002 f.e.

I assume that defining a dictionary or array could solve it but that leaves extra code.

share|improve this question
What's the question exactly? –  Jon May 2 '12 at 11:21
I want to get the uint value for COMPONENT1 using the string COMPONENT1 –  Andreas May 2 '12 at 11:23
You already have a link to the method which does exactly that. What are you having trouble with? –  Jon May 2 '12 at 11:27
it does it for enum, I want it for defined constants? –  Andreas May 2 '12 at 11:35
add comment

1 Answer

up vote 1 down vote accepted

If you don't need the constants you could go with a enum-type together with it's ToString and Parse methods.

public enum Compontents
    COMPONENT1 = 1,
    COMPONENT2 = 2

public static class ComponentsHelper
    public static Compontents GetComponent(this string compString)
        return (Compontents)Enum.Parse(typeof(Compontents), compString);

    public static uint ToValue(this Compontents comp)
        return (uint)comp;

    public static uint GetComponentValue(this string compString)
        return compString.GetComponent().ToValue();


If you really need the constants than you will have to write a big switch statement.

share|improve this answer
ok, so no way to use similar methods as the example with the enum. –  Andreas May 2 '12 at 11:28
no not for the constants - enum works because the compiler/runtime knows the possible values - no way to do this for your constants without using reflection, but I don't think that this would be advisable (performance). Just go with enum or use a global-static function with a big switch statement –  Carsten König May 2 '12 at 11:33
add comment

Your Answer


