Wednesday, 19 February 2014

how to implement icloneable c#

we implement ICloneable interface to implement prototype pattern in a .Net optimized way.

Implementing the ICloneable into the base class to create the clone type of the classes.


namespace apptest
{
    class Program
    {
        static void Main(string[] args)
        {
            BasePage<Employee> objcol = new BasePage<Employee>();
            objcol.Add(new Employee { Name = "John", Designation = "manager" });
            objcol.Add(new Employee { Name = "BOb", Designation = "Worker" });
            objcol.Add(new Employee { Name = "Eric", Designation = "Worker" });
            BasePage<Employee> objcol2 = new BasePage<Employee>();
            objcol2 = (BasePage<Employee>)objcol.Clone();
        }
           
    }
    public class Employee : BasePage<Employee>
    {
        public string Name { get; set; }
        public string Designation { get; set; }
    }
    public class BasePage : IEnumerable, ICloneable
    {
        List _arraList;
        static int _currPos = 0;
        public BasePage()
        {
            _arraList = new List();
            _currPos = 0;
        }
        #region IEnumerable Members
        public IEnumerator GetEnumerator()
        {
            foreach (T item in _arraList)
            {
                yield return item;
            }
        }
        //public IEnumerator GetEnumerator()
        //{
        //    for (int i = 0; i <= _currPos; i++)
        //        yield return _arraList[i];
        //}
        #endregion IEnumerable Members
        #region IEnumerable Members
        IEnumerator IEnumerable.GetEnumerator()
        {
            return _arraList.GetEnumerator();
        }
        #endregion IEnumerable Members
        #region IEnumerable Members
        //IEnumerator IEnumerable.GetEnumerator()
        //{
        //    for (int i = 0; i <= _currPos; i++)
        //        yield return _arraList[i];
        //}
        IEnumerator IEnumerable.GetEnumerator()
        {
            yield return this;
        }
        #endregion IEnumerable Members
        internal void Add(T Item)
        {
            _arraList.Add(Item);
        }
        public object Clone()
        {
            return this.MemberwiseClone();
        }
    }



}

No comments:

Post a Comment

Others

You will like to read it