C # Find variable by value

I am making an "error code to String" converter that will display the name of the error code from its value, for example it 0x000000c3

will give "Class not found"

, but using MY OWN error codes!

This is what it actually looks like:

#region errcodes
    public int NORMAL_STOP      = 0x00000000;
    public int LIB_BROKEN       = 0x000000a1;
    public int RESOURCE_MISSING = 0x000000a2;
    public int METHOD_NOT_FOUND = 0x000000a3;
    public int FRAMEWORK_ERROR  = 0x000000b1;
    public int UNKNOWN          = 0x000000ff;
#endregion
    public string getName(int CODE)
    {

    }

      

I would like to get the value string

from a parameter CODE

, in a function getName

.

How can i do this?

+3


source to share


1 answer


Good C # practice is to use an enum:

public enum ErrorCode
{
    NORMAL_STOP      = 0x00000000,
    LIB_BROKEN       = 0x000000a1,
    RESOURCE_MISSING = 0x000000a2,
    METHOD_NOT_FOUND = 0x000000a3,
    FRAMEWORK_ERROR  = 0x000000b1,
    UNKNOWN          = 0x000000ff
}

public const string InvalidErrorCodeMessage = "Class not found";

public static string GetName(ErrorCode code)
{
    var isExist = Enum.IsDefined(typeof(ErrorCode), code);
    return isExist ? code.ToString() : InvalidErrorCodeMessage;
}

public static string GetName(int code)
{
    return GetName((ErrorCode)code);
}

      

Another good tip, it would be great to use the C # naming convention for error codes:



public enum ErrorCode
{
    NormalStop      = 0x00000000,
    LibBroken       = 0x000000a1,
    ResourceMissing = 0x000000a2,
    MethodNotFound  = 0x000000a3,
    FrameworkError  = 0x000000b1,
    Unknown         = 0x000000ff
}

      

Usage example:

void Main()
{
  Console.WriteLine(GetName(0)); // NormalStop
  Console.WriteLine(GetName(1)); // Class not found
  Console.WriteLine(GetName(ErrorCode.Unknown)); // Unknown
}

      

+6


source







All Articles