Cast enum to integer - c#

I have an enum class called Gender, and I have values in this like:
public enum GENDER
{
MALE = 1,
FEMALE = 2,
OTHERS = 3,
}
And in my business object I just created a property for this, like:
public GENDER Gender
{
get
{
return gender;
}
set
{
gender = value;
}
}
In my database it's in type integer. For this I tried to assign the Gender value in the add function by its name Gender. But it's showing an error. Is it possible to cast the enum to integer so that it'll get the value automatically.
How can I fix this?

(int)Gender will do it. To cast a specific value instead of the property, you'll do something like (int)GENDER.MALE;

Enums by default "inherit" from int (they are stored in int by default unless you choose another integral type), so you can simply cast to and from int without any trouble:
int i = (int)GENDER.MALE;
GENDER g = (GENDER)2;
Note that implicit casting is not supported. Casting must be explicit.
Beware that the cast doesn't do any checks of the range, so you can cast an int that doesn't have a GENDER value into a GENDER variable without error:
GENDER g = (GENDER)26;

If (int)Gender is not enough to fix your cast issue, try to add int.Parse(var, int) in your code. It might be helpful...

You should be able to use a cast to convert between an integer and an enum value.
int n = (int)GENDER.MALE;
GENDER g = (GENDER)1;
If you're dealing with a string that you are reading from a database column (or any string for that matter) you can do the following:
GENDER g = (GENDER) Enum.Parse(typeof(GENDER), "MALE");
Note that Enum.Parse returns an object, so you have to cast it to your enum type first.

If you want to set the database value to gender property, do this:
yourintdatabasefiled = (int)GENDER.yourproperty

The following examples should suffice:
int val = (int)Gender.Male;
int val2 = (int)_gender;
There are also System.Enum methods to help you discover and manipulate enum values like:
Console.WriteLine("The values of the Gender Enum are: ");
foreach (int i in Enum.GetValues(typeof(Gender)))
{
Console.WriteLine(i);
}

The previous answers is right on it. Gender is now a type, just like int, so you can cast accordingly - both ways, too:
(int)Gender = . . .
/* Or */
(Gender)int = . . .
so, for
int i = (int)GENDER.male;
i would equal 1.
And the same for
Gender = GENDER.male;
i = (int)Gender;
i would also be 1.

Related

Convert and get maximum

I have an list of object which is have string "Value1" property and it is actually double.
So, I just want to get maximum and minimum values from my list with converting the property double.
That is my class.
public class Function
{
public int Id { get; set; }
public string Value1 { get; set; }
public string Value2 { get; set; }
}
I have a List<Function> and I need to get minimum "value1". Btw I am pretty sure about value1 can convertible to double. Is it possible to do this action in one line ?
What about simple casting?
myList.Max(x => double.Parse(x.Value1));
if you indeed want the min and the max, and you are sure the strings are all doubles:
string[] values = new[] { "1.1", "1.5", "2.654987" };
var doubles = values.Select(Convert.ToDouble);
var min = doubles.Min();
var max = doubles.Max();
LINQ can make it look nice
var sum = list.Select(item => item.Value1).Select(double.Parse).Sum();
You can pass a double.Parse function as parameter to the Select.
Notice that double.Parse will throw exception if Value1 is not valid double
It does matter whether you run your statement against database or not. if you do so and you do in one connection, so you will need to make all values in the same length as 'string' via a 'Select' statement and 'SqlFunctions.Replicate', and then 'Max' is going to work; but if your value contains decimals you will have trouble. Another way to escape from this solution is to fetch all value into memory using 'ToList' for instance; after that cast 'string' value to 'double' to get 'Max' statement working. but the downside is that all values is fetched into memory once

Retrieving integer values from an enum

I have defined an enum and tried to retrieve it as follows
class Demo
{
enum hello
{
one=1,
two
}
public static void Main()
{
Console.WriteLine(hello.one);
Console.ReadLine();
}
}
Now, how do i retrieve the integer value "1" from the enum ?
There's an explicit conversion from any enum type to its underlying type (int in this case). So:
Console.WriteLine((int) hello.one);
Likewise there's an explicit conversion the other way:
Console.WriteLine((hello) 1); // Prints "one"
(As a side note, I'd strongly advise you to follow .NET naming conventions, even when writing tiny test apps.)
you can cast the enums like
int a = (int)hello.one
Well you can do a cast to int
Console.WriteLine((int)hello.one);
Try This.
Console.Writeline((int)hello.Value);
or
int value = Convert.ToInt32(hello.one);

C# Copying Enumeration from one object to another

I have two very similar but not identical C# objects. I am copying the values from one class to another.
Each class has some properties that expose an enumeration type. The inside of the enumerations are the same but the names are different e.g.
public enum EnumA
{
A,
B
}
public EnumA EnumAProperty
{
get{ return enumA;}
}
public enum EnumB
{
A,
B
}
public EnumB EnumBProperty
{
get{ return enumB;}
}
I want to assign the value returned from EnumBProperty to EnumAProperty is this possible?
You can do via casting but I would not recommend it as it is fragile — if any of the enum members are reordered or new items added the result may not be what you expect.
EnumAProperty = (EnumA) EnumBProperty;
Even worse with the casting is if you have items in your source enum with no equivalent in the destination — below there are more colours than shapes:
enum Color { Red = 0, Yellow = 1, Blue = 2 };
enum Shape ( Square = 0, Triangle = 1 };
Color color = Color.Red;
Shape shape = (Shape) color;
shape could end up with the value 2 even though this value is not defined.
Instead, I'd suggest you use a switch statement to map:
EnumAProperty = ConvertToA(EnumBProperty);
...
private static EnumA ConvertToA(EnumBProperty b)
{
switch (b)
{
case EnumB.Flannel: return EnumA.HandTowel;
case EnemB.Vest: return EnumA.UnderShirt;
...
default: throw new ArgumentOutOfRangeException("b");
}
}
Each enum member has a corresponding integer value.
By default, these values are assigned in ascending order, starting with 0.
If the order of the items in the enums (and thus their numeric values) are the same, you can just cast the numeric value to EnumB to get the EnumB member with the same value:
EnumBProperty = (EnumB)(int)EnumAProperty;
If not, you need to re-parse it:
EnumBProperty = (EnumB)Enum.Parse(typeof(EnumB), EnumAProperty.ToString());
As long as both enum's of different types you can'not assign it directly.
You can define integer offset for an items so you can assign values through the integer value
public enum EnumA
{
A = 0,
B = 1
}
public enum EnumB
{
A = 0,
B = 1
}
EnumBPropertry = (int)EnumAProperty
You could either cast it to an integer or convert it to a string and then do an Enum.Parse on it.
Try the following:
EnumAProperty = (EnumA)Enum.Parse(typeof(EnumA), EnumBProperty.ToString);
EnumBProperty = (EnumB)Enum.Parse(typeof(EnumB), EnumAProperty.ToString());

Check type of object where object may be an int (32 or 64)

I would like to assign the property MyProperty with the parameter id.
The MyProperty property is of type Object, and it may be either an Int32 or an Int64.
How could I check the type of the MyProperty field and then assign it either id or id cast as an int depending on the underlying type?
public void MyMethod(long id) {
myClass.MyProperty
= (typeof(MyProperty) == typeof(long))
? id
: (int)id;
}
So you want to assign the new value based on the type of the current value? If so:
if (myClass.MyProperty is int)
{
myClass.MyProperty = (int) id;
}
else
{
myClass.MyProperty = id;
}
You can do this with a conditional expression, but it's a bit ugly:
myClass.MyProperty = myClass.MyProperty is int
? (object) id : (int) id;
Or:
myClass.MyProperty = myClass.MyProperty is int
? (object) (int) id : id;
Or to make it clear that you really, really want boxing in either case:
myClass.MyProperty = myClass.MyProperty is int
? (object) (int) id : (object) id;
You can do:
if(myClass.MyProperty is int){
..... do int stuff
}
else
{
..... do long stuff.
}
Is Operator.
As the others said, but I Recommend you use Convert instead of casting:
long l = 2147483648; // int.MaxValue + 1
int i = (int)l; // i == -2147483648 oops
i = Convert.ToInt32(l); // Overflow exception
This question does not make sense.
1. If the property is an object you can assign whatever you want. The type of an object property is object.
2. If you want to see the underlying private field... how do you know there is an underlying field to begin with? If you do know there is a private field why don't you know its type?
If you are in the very strange second case you may do 2 things.
a) Implement code in the property to do the check and conversion.
b) Decorate the property with attributes that contain metadata about the underlying field and read it via reflection.
Overall your question indicates design problem so you'd best consider redesigning instead of hacking.

Possible to load an Enum based on a string name?

OK, I don't think the title says it right... but here goes:
I have a class with about 40 Enums in it. i.e:
Class Hoohoo
{
public enum aaa : short
{
a = 0,
b = 3
}
public enum bbb : short
{
a = 0,
b = 3
}
public enum ccc : short
{
a = 0,
b = 3
}
}
Now say I have a Dictionary of strings and values, and each string is the name of above mentioned enums:
Dictionary<string,short>{"aaa":0,"bbb":3,"ccc":0}
I need to change "aaa" into HooBoo.aaa to look up 0. Can't seem to find a way to do this since the enum is static. Otherwise I'll have to write a method for each enum to tie the string to it. I can do that but thats mucho code to write.
Thanks,
Cooter
You'll have to use Reflection to get the underlying enum type:
Type t = typeof(Hoohoo);
Type enumType = t.GetNestedType("aaa");
string enumName = Enum.GetName(enumType, 0);
If you want to get the actual enum value, you can then use:
var enumValue = Enum.Parse(enumName, enumType);
Use
aaa myEnum =(aaa) Enum.Parse(typeof(aaa), "a");
You want to convert a string -> enum? This should help.
Just keep in mind that Enum.Parse isn't strongly typed... I reckon that will be a real limitation in your scenario. As you can see from Ngu's example you'd have to cast the output.

Categories

Resources