Reputation:
I'm working with some code that I don't have access to to change. This code returns a single integer, the first digit of which denotes the privilege status of the current user. For example, an elevated user with an ID of 1234 would return the userID of 11234. The same user at a non-elevated level would return 01234. Whilst this concatenates the user reference neatly, I need to store the boolean value of the users elevation separately.
I could take the first character by converting the integer to a string value - however, converting from an integer to a string, performing the operation, converting to an integer and subsequently a boolean seems unnecessary. How can I simplify this process?
bool isElevated = Convert.ToBoolean(Convert.ToInt32((resultID.ToString()).Substring(0, 1)));
Upvotes: 1
Views: 106
Reputation: 1402
The first digit of an integer cannot be zero! The only exception to this is when the integer is 0
.
You need to be careful about how the information is stored. If you're receiving an int
from someone elses auto-magic code, then you have to understand that when there is a zero in front of the int
it's going to to be clipped off because it's unimportant to a numerical value. 01 is still 1 according to the computer.
Sample code demonstrating this problem:
//Their process should add zero to beginning
bool isUserElevated = false;
//The ID before auto-magic
string yourInitialID = "1234";
//Other person's process of adding identifier
if (isUserElevated == true)
{
yourInitialID = "1" + yourInitialID;
}
else
{
yourInitialID = "0" + yourInitialID;
}
//uh oh whered my zero go
int realID = int.Parse(yourInitialID);
//The computer parsed 01234 as 1234
//Your process of identifying for bool
bool myNeededVar = false;
Console.WriteLine(realID);
Console.ReadKey();
Upvotes: 1