Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advice about building an error code lookup in C#

Tags:

c#

edsdk

I'm new to C# and so forgive me if I have some of my concepts skewed. I'm working with the Canon EDSDK, and to make life easier I'd like to be able to see error messages as text rather than hex values. The EDSDK.cs file contains a long list of errors such as :

public const uint EDS_ERR_TAKE_PICTURE_CARD_NG = 0x00008D07;
public const uint EDS_ERR_TAKE_PICTURE_CARD_PROTECT_NG = 0x00008D08;

Ideally I'd like to put all of these into some sort of lookup table so I can input a HEX errorcode and return the actual message as a string. For example

Hashtable EDSDKErrorCodes = new Hashtable();

EDSDKErrorCodes.Add("0x00008D01", "EDS_ERR_TAKE_PICTURE_AF_NG");
EDSDKErrorCodes.Add("0x00008D08", "EDS_ERR_TAKE_PICTURE_CARD_PROTECT_NG");
etc etc...

The later in my code I could grab the error message returned from one of the EDSDK methods and display it in a human readable form :

errorcode= EDSDK.EdsInitializeSDK();

MessageBox.Show(Convert.ToString(EDSDKErrorCodes[errorcode]));

My question is .. is this a good way to handle all these error codes or is there a better and more efficient way that people would recommend? If so how I could fill my hash table as a series of constants rather than having to use the Add method?

like image 603
mrbencowell Avatar asked Nov 28 '22 09:11

mrbencowell


2 Answers

Another way you could do this is by creating an Enum with a description attribute. See here for the full details. This is summarizing how it would look:

public enum ErrorCodes : uint
{
    [Description("Description for EDS_ERR_TAKE_PICTURE_CARD_NG")]
    EDS_ERR_TAKE_PICTURE_CARD_NG = 0x00008D07,
    [Description("Description for EDS_ERR_TAKE_PICTURE_CARD_PROTECT_NG")]
    EDS_ERR_TAKE_PICTURE_CARD_PROTECT_NG = 0x00008D08
}

At the very simplest, if you didnt care about a description, you could convert the enum name to string using Enum.GetName

like image 149
SwDevMan81 Avatar answered Dec 16 '22 03:12

SwDevMan81


You could use an enum for this.

public enum ErrorCodes : uint
{
    EDS_ERR_TAKE_PICTURE_CARD_NG = 0x00008D07,
    EDS_ERR_TAKE_PICTURE_CARD_PROTECT_NG = 0x00008D08
}

Then your usage could be something like the following:

ErrorCodes error = (ErrorCodes)EDSDK.EdsInitializeSDK();
MessageBox.Show(Enum.GetName(typeof(ErrorCodes), error));
like image 34
Jan-Peter Vos Avatar answered Dec 16 '22 01:12

Jan-Peter Vos