Thursday, March 1, 2018

A couple of really useful extension methods

This one can make a List<> out of a SortedList

        public static List ToList(this SortedList collection)
        {
            var list = new List();
            foreach (DictionaryEntry item in collection)
                list.Add((T)item.Value);
            return list;
        }

And this one solves the problem of trying to stuff an instance of a base class into an instance of a class derived from it.
 
      public static T As(this object donor)
        {
            var type = typeof(T);
            var instance = Activator.CreateInstance(type);

            if (type.BaseType != null)
            {
                var properties = type.BaseType.GetProperties();
                foreach (var property in properties)
                    if (property.CanWrite)
                        property.SetValue(instance,  
                        property.GetValue(donor, null),
                        null);
            }

            return (T)instance;
        }

No comments:

Post a Comment