when working with strings, I can check if it has a value by doing something like

if (s == "")

but how do I accomplish this with integers? I thought maybe initializing to a dummy value like 0 or -1, but what if those values might be valid? should I use something like -999?

I'm just wondering what the standard practice is on this situation.

thanks!

Recommended Answers

All 2 Replies

In actuality you have the same problem with strings. "" might be a valid string. Thus, the only sure way to know that a string has not been set to a valid value is to set your string object to null when it isn't initialized. I'm not positive, but I think you can do the same thing if you use Int32 instead of int.

Of course the downside with this approach is that it requires everyone who ever uses this value to check for null before applying any operations on it. But, you probably have to do this anyways if you are concerned with invalid values.

With that said, that is not the typical approach. Most people use dummy values. However, those dummy values should be assigned a name.

Thus,

if(myNumber == -999)
{
    // Do something with invalid numbers
}

is bad style.

However,

Define this somewhere:

const int INVALID_VALUE = -999;

Then later on:

if(myNumber == INVALID_VALUE)
{
    // Do something with invalid numbers
}

is the generally accepted approach.

commented: thanks for your insight! +4

nice, that's good stuff to know, and it makes a lot of sense. I will be sure to use this practice. many thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.