473,661 Members | 2,484 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cast from int to constants possible?

I've got some class which contains loads of static const int values, is
there a way that, given an int, i can quickly cast the int back to a string
representation of the const?

for eg.

MyClass contains
const int ERROR_NONE = 1
const int ERROR_NO_DRIVE = 2
const int ERROR_INSUFFICI ENT_DISK_SPACE = 3
....
etc.

and given an int value of say 3, I'm able to display an error message saying
something like:

string errMsg = "Error! Code: " + ((MyClass)(nErr orCode)).ToStri ng();

Thanks!
Nov 15 '05 #1
5 4895
<"Daniel Bass" <I'm really @ sick of spam>> wrote:
I've got some class which contains loads of static const int values, is
there a way that, given an int, i can quickly cast the int back to a string
representation of the const?

for eg.

MyClass contains
const int ERROR_NONE = 1
const int ERROR_NO_DRIVE = 2
const int ERROR_INSUFFICI ENT_DISK_SPACE = 3
....
etc.

and given an int value of say 3, I'm able to display an error message saying
something like:

string errMsg = "Error! Code: " + ((MyClass)(nErr orCode)).ToStri ng();


No. Instead of having consts, use an enumeration instead - then you get
type safety *and* you can go back to the name easily.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2
No. Instead of having consts, use an enumeration instead - then you get
type safety *and* you can go back to the name easily.


I would, but the class of constants isn't mine, stupid for me to put
"MyClass"!! !

Should've put "ClassOfConstan tsGivenToMeThat ICan'tAlter" ! ;o)

Agree that enums are far superior.

Thanks.
Dan.

Nov 15 '05 #3
<"Daniel Bass" <I'm really @ sick of spam>> wrote:
No. Instead of having consts, use an enumeration instead - then you get
type safety *and* you can go back to the name easily.


I would, but the class of constants isn't mine, stupid for me to put
"MyClass"!! !

Should've put "ClassOfConstan tsGivenToMeThat ICan'tAlter" ! ;o)

Agree that enums are far superior.


I'd define an enumeration with the same values, and use that everywhere
you can. Where you can't, just cast from the int to the enum type. Does
that help? The only problem is what happens if the set of errors
changes - do you get new versions of this class on a regular basis?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #4

It's IBM's MQSeries .Net interface.
(
http://www-1.ibm.com/support/docview...&cc=us&lang=en )

I prefer MSMQ for messages, IBM's version is too clever and mucks up every
time.

So when you a catch an expection, you ask for the message and it gives you
back something like " Code: 2, Reason: 2018", which might be something like
invalid queue handle, but there's no way of easily checking that.

If i press F12 to check the definition, it brings up the object explorer for
the class which doesn't say what the values of each const int is.

Thanks for your time.
Dan.

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
<"Daniel Bass" <I'm really @ sick of spam>> wrote:
No. Instead of having consts, use an enumeration instead - then you get
type safety *and* you can go back to the name easily.


I would, but the class of constants isn't mine, stupid for me to put
"MyClass"!! !

Should've put "ClassOfConstan tsGivenToMeThat ICan'tAlter" ! ;o)

Agree that enums are far superior.


I'd define an enumeration with the same values, and use that everywhere
you can. Where you can't, just cast from the int to the enum type. Does
that help? The only problem is what happens if the set of errors
changes - do you get new versions of this class on a regular basis?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #5
100
Agree that enums are far superior.

Not always, though.
Imagin that we have class hierarchy for Items let say

public enum ItemType{Pencil , Notebook}
public class abstract Item
{
public abstract ItemType Type
{
get;
}
}
class Pencil: Item
{
public override ItemType Type
{
get{return ItemType.Pencil ;}
}

}
class Notebook: Item
{
public override ItemType Type
{
get{return ItemType.Notebo ok;}
}
}

If you use enums for the type as I do. You cannot extend the hierarchy with
new Items because you cannot inherit the enumeration.

But if we had
public class abstract Item
{
public abstract int Type
{
get;
}
}

and

public class ItemType
{
public const int Pencil = 1;
public const int NoteBook = 2;
}

So, we could do
class MyItemTypes: ItemType
{
public const int Staple = 3;
}

What you can do in your case is

class MyNewClass: MyClass
{
private int mErrCode;
public static explicit operator MyNewClass(int errCode)
{
MyNewClass res = new MyNewClass();
res.mErrCode = errCode;
return res;
}
public override string ToString()
{
string res = "";
switch(mErrCode )
{
case 1:
res = "ERROR_NONE ";
break;
case 2:
res = "ERROR_NO_DRIVE ";
break;
case 3:
res = "ERROR_INSUFFIC IENT_DISK_SPACE ";
break;
default:
res = "UNKNOWN ERROR";
break;
}
return res;
}
}

Now you can write

string errMsg = "Error! Code: " + ((MyNewClass)nE rrorCode).ToStr ing();

or

string errMsg = "Error! Code: " + ((MyNewClass)2) .ToString();
Ofcourse with enums it would be easier, but since you don't have control
over it this will work for you.

HTH
B\rgds
100
Nov 15 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
3053
by: David W. Fenton | last post by:
Today I was working on a hideous old app that I created a long time ago that does a lot of showing/hiding/resizing of fields on one of the forms. I had used constants to store reference values for many of the top/height/left settings. I noticed that some of the constants were defined by using other constant values, and I was impressed that VBA could do that. Here's an example: Const row1Top = 1.0208 * 1440 ' top of first row Const...
10
2599
by: LaEisem | last post by:
On-the-job, I have "inherited" a lot of old C language software. A question or two about when "casting" of null pointer constants is needed has occurred during behind-the-scenes cleanup of some of that software. That subject seems not to be addressed, at least not directly, in the C FAQ where FAQ 5.2 seems most relevant. References: * C FAQ 5.2 Null pointers (Including conditions where "casting" of null pointer...
4
10460
by: Ray | last post by:
When a single-bit bitfield that was formed from an enum is promoted/cast into an integer, does ANSI C say anything about whether that integer should be signed or unsigned? SGI IRIX cc thinks it is an unsigned integer, so I see a +1 if the bit is set. Microsoft VC++ thinks it's signed, so I see -1 if the bit is set. Ex. typedef enum {
9
7125
by: rsine | last post by:
I have developed a program that sends a command through the serial port to our business system and then reads from the buffer looking for a number. Everything worked great on my WinXP system, but when I tried the program on the Win98 system it will be running on, I get the following error: Cast from string "2076719" to type 'Long' is not valid I am not sure why I only get this error on the Win98 system or how to go about correcting...
12
2683
by: Ralf | last post by:
If you want to explicitly state the type of an integer constant, you basically have two options. Either you use an explicit cast, as in: (unsigned int) 1234 or you use the UL suffixes, as in: 1234UL Are there -- in general -- any semantic differences in using casts versus suffixes? --Ralf
9
2715
by: Frederick Gotham | last post by:
Let's assume that we're working on the following system: CHAR_BIT == 8 sizeof( char* ) == 4 (i.e. 32-Bit) Furthermore, lets assume that the memory addresses are distributed as follows: 0x00000000 through 0xFFFFFFFE : Valid byte addresses
9
12922
by: Hamish M | last post by:
Hi I am interested in opinions on this topic. I have heard that a suffix is not a good solution and type casts are much better for example. ----------------------------------------------------------------- #define MAX_UWORD (T_UWORD)65535
6
3122
by: PC | last post by:
Gentlesofts, Forgive me. I'm an abject newbie in your world, using VB 2005 with the dot-Net wonderfulness. So, I'm writing a wonderful class or two to interface with a solemnly ancient database. In times recently past, I would have done this with Borland Delphi. So, that's my perspective and I have my old Delphi code to crib from. That seems good.
54
3587
by: shuisheng | last post by:
Dear All, I am always confused in using constants in multiple files. For global constants, I got some clues from http://msdn.microsoft.com/en-us/library/0d45ty2d(VS.80).aspx So in header file writing: const double PI = 3.14; Every time using it, include the header file.
0
8432
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8856
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8762
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8545
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8633
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5653
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2762
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1992
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1747
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.