is it possible to make a default typecast for an enum?
I use enum for a lot, such as states and I want to compare enums directly to LINQ fields, but I have to typecast all the time.
is it possible to make a default typecast for an enum?
I use enum for a lot, such as states and I want to compare enums directly to LINQ fields, but I have to typecast all the time.
You should be able to have properties in your LINQ objects that have an enum type. This way you do not have to cast.
So just change your properties to have the correct enum type and you don't have to worry about casts any longer. You can do this in the LINQtoSQL designer. Just right-click on a property, select 'Properties' and set the appropriate Type in the Visual Studio Properties window.
Have you tried extension methods?
public enum MyEnum
{
First = 1,
Second = 2,
Third = 3
}
public static class Utility
{
public static string Description(this Enum e)
{
Type t = e.GetType();
DescriptionAttribute[] desc =
(DescriptionAttribute[])(t.GetField(e.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false));
return desc.Length > 0 ? desc[0].Description : e.ToString();
}
public static byte ToByte(this Enum ai)
{
object o=Enum.ToObject(ai.GetType(), ai);
return Convert.ToByte(o);
}
}
class Program
{
static void Main(string[] args)
{
MyEnum me = MyEnum.Third;
Console.WriteLine("Value: {0}\r\nType: {1}"
,me.ToByte(),me.ToByte().GetType().ToString());
Console.ReadLine();
}
}
It outputs:
Value: 3
Type: System.Byte
LINQ-to-SQL will usually handle direct integer maps and exact string (name) maps (note: case sensitive). Meaning: write your enum somewhere, and in the designer set the property type as the fully-qualified enum name: Some.Namespace.MyEnum
. It should usually work.
For non-trivial mappings (for example where the column is a varchar with mixed-case values, or things like "In Progress" [note the space]), you will have to leave the storage property as int
/varchar
(etc) and map it manually. I usually do this by marking it as private and naming it FooStorage
, and adding a mapping property in a partial class:
partial class MyType {
public MyEnum Foo {
get {... mapping logic reading from FooStorage...}
set {... mapping logic, updating FooStorage...}
}
}
The only problem is that LINQ queries will only work against the storage property (not the bespoke property).
The answer was MUCH more simple!!!
A good friend of mine told me this is very simple! have a look at this sample!
public enum State:byte
{
EmailNotValidated = 0x00,
EmailValidated = 0x10,
Admin_AcceptPending = 0x40,
Active = 0x80,
Admin_BlockedAccount = 0xff
}
Pay attention to the :BYTE part after the name of the Enum... there is the trick I was looking for! But thanks to everyone trying for me!
Looking forward to post my next question.