Convert output of string to a number value - c#

I have the following code
Call.Direction CallDir = details.dir;
and the output is either In or out.
my question how can I convert the output to be as follow:
if CallDir value is In ===> display 0
if CallDir value is Out ===> display 1

Okay, so if you wanted to return a different value based on the enum, just do this:
return CallDir == Call.Direction.In ? 0 : 1;
However, if what you're saying is details.dir is a string of In or Out and you need to get that into an enum, then do this:
Call.Direction CallDir;
if (!enum.TryParse<Call.Direction>(details.dir, out CallDir))
{
// set it to some default value because it failed
}

In addition to what Michael said, if your enum is defined with the appropriate values, you can simply cast it to an int.
enum CallDirection { In = 0, Out = 1 }
var dir = CallDirection.In;
Console.Write((int)dir); // "0"

Related

Increment an enumeration value to the next one

I have an enumeration like so:
[Flags]
public enum UserProcessStage : uint
{
ShopSelection = 1,
FillBasket = 2,
SpecifyShipmentCredentials = 4,
SpecifyPaymentCredentials = 8,
OrderComplete = 16
}
Assuming I have a variable whose value is FillBakset (2), what I want to do is be able to increment it to the next value that is defined within the enumeration (SpecifyShipmentCredentials, 4).
The problem is that incrementing it causes its value to be 3 since it is based on an integer, I tried multipliying it by 2 but got a compilation error.
How could I increment an enumeration value to the next one ?
Thanks
You can use this code. It basically orders the enum by underlying value and then givs you the first enum which is bigger than the one specified. If none found, it will return 0 because of DefaultIfEmty():
public static UserProcessStage GetNext(UserProcessStage value)
{
return (from UserProcessStage val in Enum.GetValues(typeof (UserProcessStage))
where val > value
orderby val
select val).DefaultIfEmpty().First();
}

Is there a better way to check for valid values?

I have a property in my class that can only be one of several values, what is the best way to limit the input on this property.
Here is what I'm doing now, and I'm sure there must be a better way.
public void SetValue(int value)
{
if(value != 1 ||
value != 4 ||
value != 8 ||
value != 16 ||
value != 32 ||
value != 64, ||
value != 128)
{
property_value = 1;
}
else
{
property_value = value;
}
}
Instead of in int, use an Enum with these values.
I am sure each value has a specific meaning - expose these as enum members.
This may not eliminate all issues (since an Enum is simply a wrapper over an integer type and can still get assigned a value that doesn't exist in the enumeration), but should take care of most problems, so long as you are consistent about only passing values from the enumeration itself.
In any rate, you can then simply test the passed in value against the enumeration and throw an exception if it isn't a valid member.
Use enum instead of this numeric values like:
enum Numbers { Name1 = 1, Name2 = 4 ... }
and then you can easilly check if value is one of enum element:
Enum.IsDefined(typeof(Numbers), value );
For your example, you can just do:
property_value = 1;
since your if condition will always be true.
If you want to restrict it to a number of possibilities you could:
Declare an enum:
public enum Value
{
Default = 1,
Option1 = 4,
...
}
or have a collection of valid values to check:
int[] validValues = new int[] { 1, 4, 8, 16, 32, 64, 128 };
property_value = validValues.Contains(value) ? value : 1;
Although I would prefer to throw an exception on invalid input.
I think you should consider using an enum:
public enum MyEnum
{
These,
Are,
Valid,
Values
}
public void SetValue(MyEnum _value)
{
// Only MyEnum values allowed here!
}
if(((value & (value − 1)) == 0) && value != 2 && value <= 128)
property_value = 1;
else
property_value = value;
(value & (value − 1)) is a fast way to check if value is a power of two.
As an example: value = 4:
(4(10) & (3(10)) =
100(2) & 011(2) =
000(2) = 0
value = 5
(5(10) & (4(10)) =
101(2) & 100(2) =
100(2) =
4
You could use an enum and check using Enum.IsDefined(value). But then you'd have to think of a (meaningfull) name for all the possible values.
I think we're missing the INTENT of the function here.
It looks like a bit mask check to me. If that's the case, he's missing 2 from the code sample. Also, note that he's not discarding a value if it isn't one of those specific bits: he preserves it. If it is a value equal to a specific bit (and only that bit) he coerces it to 1.
I think the sample provided by Lee works best in this case; it's simple and to the point. Also, if the check is widened to account for 16 bits (or even 32), it will easily catch them all.

Convert integer enum to string

considering the following enum:
public enum LeadStatus
{
Cold = 1,
Warm = 2,
Hot = 3,
Quote = 5,
Convert = 6
}
How can I convert the integer value back to string when I pull the value from a database. I've tried:
DomainModel.LeadStatus status = (DomainModel.LeadStatus)Model.Status;
but all I seem to get is "status = 0"
What you are looking for is Enum.Parse.
"Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object."
Here is the MSDN page: http://msdn.microsoft.com/en-us/library/essfb559.aspx
Example:
enum Colour
{
Red,
Green,
Blue
}
// ...
Colour c = (Colour) Enum.Parse(typeof(Colour), "Red", true);
Courtesy of http://blogs.msdn.com/tims/archive/2004/04/02/106310.aspx
Between Enum.Parse and Enum.ToString, you should be able to do everything you need.
Given "Model.Status" is the integer from the database, it can be restored to the Enum string value with:
string status = Enum.GetName(typeof(DomainModel.LeadStatus), Model.Status);
Just use ToString() on the enum object
An enumeration in C# is used to provide names for some known values but ANY integer value is permissible in that enumeration, whether it has a named equivalent or not.
In your example, you have not named a zero value, but your status variable initialises to zero. I suspect that it has not changed from this initial value at the point you read it. Therefore, it's string representation is also 0 and you will parse out zero when you parse it.

enum name with multiple values

In my project i'm using enums example:
public enum NcStepType { Start = 1, Stop = 3, Normal = 2 }
i'm reading values from a database, but sometimes there are 0-values in my record, so i want an enum that looks like
public enum NcStepType { Start = 1 OR 0, Stop = 3, Normal = 2 }
is this possible (in c#) ?
You could create a generic extension method that handles unknown values:
public static T ToEnum<T>(this int value, T defaultValue)
{
if (Enum.IsDefined(typeof (T),value))
return (T) (object) value;
else
return defaultValue;
}
Then you can simply call:
int value = ...; // value to be read
NcStepType stepType = value.ToEnum(NcStepType.Start);
// if value is defined in the enum, the corresponding enum value will be returned
// if value is not found, the default is returned (NcStepType.Start)
No, basically. You would have to give it one of the values (presumably the 1), and interpret the other (0) manually.
No it is not, and I'm not sure how it would work in practice.
Can't you just add logic that maps 0 to 1 when reading from the DB?
Normally i define in such cases the 0 as follows:
public enum NcStepType
{
NotDefined = 0,
Start = 1,
Normal = 2,
Stop = 3,
}
And somewhere in code i would make an:
if(Step == NcStepType.NotDefined)
{
Step = NcStepType.Start;
}
This makes the code readable and everyone knows what happens... (hopefully)
No, in C# an enum can have only one value.
There's nothing that says the value in the database must map directly to your enum value however. You could very easily assign a value of Start whenever you read 0 or 1 from the database.
public enum NcStepType { Start = 1 | 0, Stop = 3, Normal = 2 }
No solution in C#. But you can take 2 steps:
1. Set default value of your DB field to 1.
2. Update all existing 0 to 1.
As far as I know you can write this
enum NcStepType { Start = 0, Start = 1, Stop = 3, Normal = 2 }
The only problem is later there would be no way telling which Start was used for variable initialization (it would always look like it was the Start = 0 one).

Error on if statement - cannot implicitly convert type to 'bool'

I am having an issue converting type. I was trying code like this (minimal, detailed code later):
string cityType = "City1";
int listingsToSearch = 42;
if (cityType = "City1") // <-- error on this line
{
listingsToSearch = 1;
}
But "if" statement to convert the cities but I keep getting:
cannot implicitly convert type 'string' to 'bool'
What I'm trying to achieve: I have a search engine that has a textbox for the search text and two radio buttons for the search location ( IE City1 or City2 )
When I receive the search text and radio buttons they are in the form of a string
string thesearchtext, thecitytype;
thesearchtext = HttpContext.Current.Request.QueryString["s"].ToString();
thecitytype = HttpContext.Current.Request.QueryString["bt"].ToString();
When I receive the cities radiobutton they will be in the format of "city1" or "city2".
What i need to do is convert the city radiobuttons into an int so that I can use them in my search dataset. I need to convert "city" to integer 1 and "city2" to integer 2.
I understand this is probably a simple type conversion however I just cannot figure it out. So far code with if gives me error above:
int listingsToSearch;
if (thecitytype = "City1")
{
listingsToSearch = Convert.ToInt32(1);
}
else
{
listingsToSearch = Convert.ToInt32(2);
}
c# equality operator is == and not =:
if (thecitytype == "City1")
Here is some code in you can use with NUnit that demonstrates another technique for calculating listingToSearch - You will also notice that with this technique, you won't need to add extract if/else, etc as you add more cities - the test below demonstrates that the code will just try to read integer starting after "City" in the radio button label. Also, see the very bottom for what you could write in your main code
[Test]
public void testGetCityToSearch()
{
// if thecitytype = "City1", listingToSearch = 1
// if thecitytype = "City2", listingToSearch = 2
doParseCity(1, "City1");
doParseCity(2, "City2");
doParseCity(20, "City20");
}
public void doParseCity(int expected, string input )
{
int listingsToSearch;
string cityNum = input.Substring(4);
bool parseResult = Int32.TryParse(cityNum, out listingsToSearch);
Assert.IsTrue(parseResult);
Assert.AreEqual(expected, listingsToSearch);
}
In your regular code you can just write:
string thecitytype20 = "City20";
string cityNum20 = thecitytype20.Substring(4);
bool parseResult20 = Int32.TryParse(cityNum20, out listingsToSearch);
// parseResult20 tells you whether parse succeeded, listingsToSearch will give you 20

Categories