C# Shallow Copy / Downcasting

15. March 2011 09:56

Today I found that the child class can't be passed over a WCF service as the base class.  I tried using the KnownType and ServiceKnownType attributes, which did allow the transfer, but then EntityFramework didn't like the child class.  My solution was to write a quick shallow copy function.  Enjoy!

 

public static class Copy
    {
        public static T Shallow< T>(this object source)
        {
            return Shallow< T>(source, (T)Activator.CreateInstance(typeof(T)));
        }
        public static T Shallow<T>(this object source, T target)
        {
            foreach (PropertyInfo pi in typeof(T).GetProperties())
            {
             var prop =  source.GetType().GetProperty(pi.Name);
                    
                if(prop != null)
                    prop.SetValue(target, pi.GetValue(source, null), null);
            }
            return target;
        }


    }

blog comments powered by Disqus

Custom Development

ALL USA BASED DEVELOPERS

 

Coder For Rent is a one-stop shop for all your .Net programming needs.  We can make project-based fixed bids as well as hourly/weekly/monthly quotes.  Our goal is to meet your needs the first time, saving you time and money.

 

Call to speak with an account manager. We take projects of all sizes.

 

713-482-7155 

Contact Us

Call 713-482-7155 
for technical or purchasing support

Freshbooks Rocks

FreshBooks

Silverlight Gantt Chart Control
Silverlight Scheduler Control