1 apr 2012

Working with Enums


What is an ENUM

Enum is the short for enumeration. it can be use-full to make your code more readable.
For example :
We have a Class Named Person.cs and this class has a property "Status".

without use of Enums
Person.status = 3;

It doesnt tell us what the status stands for.

with use of Enums

using System;
public enum MyEnumeration
    {
        Single = 1,
        Married= 2,
        Widow = 3
    }


Person.status = MyEnumeration.Widow;

Another Advantage of using enums is the following situation.

We Forgot to add the Devorced Status.

We change our Enum :

public enum MyEnumeration
    {
        Single = 1,
        Married= 2,
        Devorced = 3,
        Widow = 4
    }


if we coded without enum, the status of the person is changed from Widow to Devorced.
With use of enum, the status is still Widow after adding the devorced state


SIMPLE ENUM OPERATIONS
string Mystring = "Single";
int intval = 3;

            
 //string to enum
//----------------------------------------------
     //without extention methodMyEnumeration myitem = (MyEnumeration)Enum .Parse(typeof( MyEnumeration), Mystring);
     //with extention method                              
MyEnumeration item = Mystring.ParseToEnum<MyEnumeration >();

         
 //int to enum
//----------------------------------------------
     //without extention method
MyEnumeration item = (MyEnumeration )intval;
     //with extention method                                  
MyEnumeration item2 = intval.ParseToEnum<MyEnumeration >();

//enum to string
//----------------------------------------------
     //without extention method
string name1 = Enum .GetName(typeof( MyEnumeration), MyEnumeration.Married);
     //with extention method
string name = MyEnumeration .Married.GetName();

 //enum to int
//----------------------------------------------
     //without extention method
int val = (int )MyEnumeration.Married;
      //with extention method                                  
int val1 = MyEnumeration .Married.GetValue();


Loop Trough enum

 foreach ( string value in Enum.GetNames( typeof(MyEnumeration)))
            {
                valueList.ValueListItems.Add(value);
            }



Extention methods to work with enums

        public static int GetValue( this Enum EnumValue)
        {
            return (int )(Enum.ToObject(EnumValue.GetType(),EnumValue));
        }
        public static string GetName( this Enum EnumValue)
        {
            return (Enum .GetName(EnumValue.GetType(),EnumValue));
        }
        public static T ParseToEnum(this string value)
        {
            Type TypeOfDestObj = typeof (T);
            if (!TypeOfDestObj.IsEnum) throw new ArgumentException("is no enum" );
            return (T)Enum .Parse(TypeOfDestObj, value);
        }
        public static T ParseToEnum(this int value)
        {
            Type TypeOfDestObj = typeof (T);
            if (!TypeOfDestObj.IsEnum) throw new ArgumentException("is no enum" );
            return (T)Convert .ChangeType(value, TypeOfDestObj);
        }


Extention methods to loop trough enums


         public static Dictionary< int string > ToDictionaryWithValueAsKey( this object obj)
        {
            Dictionary <int string> rets = new Dictionary < intstring >();
            Type MyType = obj.GetType();
            if (!MyType.IsEnum) throw new ArgumentException ("is not an enum" );
            var vals = Enum .GetValues(MyType);
            var names = Enum .GetNames(MyType);
            for (int i = 0; i < names.Length; i++)
            {
                int val = (int )vals.GetValue(i);
                string name = names.GetValue(i) as string;
                rets.Add(val, name);
            }
            return rets;
        }


        public static Dictionary< string int > ToDictionaryWithNameAsKey( this object obj)
        {
            Dictionary <string int> rets = new Dictionary < stringint >();
            Type MyType = obj.GetType();
            if (!MyType.IsEnum) throw new ArgumentException ("is not an enum" );
            var vals = Enum .GetValues(MyType);
            var names = Enum .GetNames(MyType);
            for (int i = 0; i < names.Length; i++)
            {
                int val = (int )vals.GetValue(i);
                string name = names.GetValue(i) as string;
                rets.Add(name,val);
            }
            return rets;
        }

What to do if you need String Values instead of int values

You can also use other types than int. 

But what to do with strings?


1. Create a Custom attribute 

    public class StringValueAttribute : System.Attribute
    {
        private string _value;

        public StringValueAttribute(string value)
        {
            _value = value;
        }

        public string Value
        {
            get { return _value; }
        }
    }


2. Add the custom attribute to the enum

    public enum MyEnumeration
    {
        [ StringValueAttribute("Y" )]
        Young = 1,
        [ StringValueAttribute("M" )]
        Middelaged = 2,
        [ StringValueAttribute("O" )]
        Old = 3
    }


2.  Create an ExtentionMethod to get te stringvalue 

         public static string GetStringValue( this Enum value)
        {
            return (from members in value.GetType().GetMember(value.ToString())
let atts= (StringValueAttribute)members.GetCustomAttributes(typeof (StringValueAttribute), false).FirstOrDefault()
                    select attributes == null ? value.ToString() : attributes.Value).FirstOrDefault();
        }

3.  Use it

             int intval = 3;
            MyEnumeration item3 = intval.ParseToEnum<MyEnumeration >();
            string stringval = item3.GetStringValue();

2 mrt 2012

referring to Parent object Best Practices? c#

Dont ask me wath the best solution is.
but they work for me
please comment your opinion about the best choice
 SOLUTION WITH DELEGATES

    /// 

    /// Parrent Object
    /// 
    public class Parent : ObservableCollection<child>
    {
        public string Name;
        public new void AddChild(string name)
        {
            child NewItem = new child();
            NewItem.OtherParameter = name;
            NewItem.GetParentEvent += new Func<Parent>(item_GetParentEvent);
            base.Add(NewItem);
        }
        Parent item_GetParentEvent() { return this; }
    }


   /// 

    /// Child Object
    /// 
    public class child
    {
        public string OtherParameter;
        private event Func<Parent> getParentEvent;
        public event Func<Parent> GetParentEvent
        {// First try to remove the handler, then re-add it
            add
            {               
                getParentEvent -= value;
                getParentEvent += value;
            }
            remove{getParentEvent -= value;}
        }
        private Parent _ParentItem;
        [System.Xml.Serialization.XmlIgnoreAttribute]
        public Parent ParentItem
        {
            get{GetParrent();
                return _ParentItem;}
            set{_ParentItem = value;}
        }
        private void GetParrent()
        {
            if (getParentEvent != null){ParentItem = getParentEvent();}
        }
  

     
        public class FamilyClass
        {
            Parent MyDad = new Parent();
            Parent MyMam = new Parent();
           public void ExecuteTime()
           {
                MyDad.Name = "My Daddy";
                MyDad.AddChild("Me myself and i");
                Console.WriteLine(MyDad.ElementAt(0).ParentItem.Name);
                MyDad.Name = "My Daddy's split personality";
                Console.WriteLine(MyDad.ElementAt(0).ParentItem.Name);
                MyMam.Name = "My Mam";
                child MySelf = MyDad.ElementAt(0);
                MySelf.GetParentEvent += new Func<Parent>(MySelf_GetParentEvent);
                Console.WriteLine(MySelf.ParentItem.Name);
                Console.ReadLine();
           }
           Parent MySelf_GetParentEvent()
           {
               return MyMam;
           }                            
        }
        static void Main(string[] args)
        {
            FamilyClass   bb = new FamilyClass();
            bb.ExecuteTime();         
        }    




SOLUTION WITH CONTSTRUCTOR

    public class Parent : ObservableCollection<child>
    {
        public string Name;
        public new void Add(string name)
        {
            child NewItem = new child(this) { OtherParameter = name };
            base.Add(NewItem);
        }
    }



    public class child
    {
        public child(Parent MyParentObject)
        {
            _ParentItem = MyParentObject;
        }

        readonly Parent _ParentItem;
        public string OtherParameter;
        public Parent ParentItem
        {
            get { return _ParentItem; }
        }
    }



 static void Main(string[] args)
        {
             Parent MyDad = new Parent();
            MyDad.Name = "My Dad";
            MyDad.Add("ikke");
            Console.WriteLine(MyDad.ElementAt(0).ParentItem.Name);
            MyDad.Name = ""My Daddy's split personality";
            Console.WriteLine(MyDad.ElementAt(0).ParentItem.Name);
            Console.ReadLine();
        }