Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7717645
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T02:57:15+00:00 2026-06-01T02:57:15+00:00

I have the following code which copies property values from one object to another

  • 0

I have the following code which copies property values from one object to another objects by matching their property names:

public static void CopyProperties(object source, object target,bool caseSenstive=true)
    {
        PropertyInfo[] targetProperties = target.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
        PropertyInfo[] sourceProperties = source.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo tp in targetProperties)
        {
            var sourceProperty = sourceProperties.FirstOrDefault(p => p.Name == tp.Name);
            if (sourceProperty == null && !caseSenstive)
            {
                sourceProperty = sourceProperties.FirstOrDefault(p => p.Name.ToUpper() == tp.Name.ToUpper());
            }
            // If source doesn't have this property, go for next one.
            if(sourceProperty ==null)
            {
                continue;
            }

            // If target property is not writable then we can not set it; 
            // If source property is not readable then cannot check it's value 
            if (!tp.CanWrite || !sourceProperty.CanRead)
            {
                continue;
            }

            MethodInfo mget = sourceProperty.GetGetMethod(false);
            MethodInfo mset = tp.GetSetMethod(false);

            // Get and set methods have to be public 
            if (mget == null)
            {
                continue;
            }

            if (mset == null)
            {
                continue;
            }


            var sourcevalue = sourceProperty.GetValue(source, null);
            tp.SetValue(target, sourcevalue, null);

        }
    }

This is working well when the type of properties on target and source are the same. But when there is a need for casting, the code doesn’t work.

For example, I have the following object:

class MyDateTime
{
    public static implicit operator DateTime?(MyDateTime myDateTime)
    {
        return myDateTime.DateTime;
    }

    public static implicit operator DateTime(MyDateTime myDateTime)
    {
        if (myDateTime.DateTime.HasValue)
        {
            return myDateTime.DateTime.Value;
        }
        else
        {
            return System.DateTime.MinValue;
        }
    }

    public static implicit operator MyDateTime(DateTime? dateTime)
    {
        return FromDateTime(dateTime);
    }

    public static implicit operator MyDateTime(DateTime dateTime)
    {
        return FromDateTime(dateTime);
    }
 }

If I do the following, the implicit cast is called and everything works well:

MyDateTime x= DateTime.Now; 

But when I have a two objects that one of them has a DateTime and the other has MyDateTime, and I am using the above code to copy properties from one object to other, it doesn’t and generate an error saying that DateTime can not converted to MyTimeDate.

How can I fix this problem?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T02:57:16+00:00Added an answer on June 1, 2026 at 2:57 am

    One ghastly approach which should work is to mix dynamic and reflection:

    private static T ConvertValue<T>(dynamic value)
    {
        return value; // This will perform conversion automatically
    }
    

    Then:

    var sourceValue = sourceProperty.GetValue(source, null);
    if (sourceProperty.PropertyType != tp.PropertyType)
    {
        var method = typeof(PropertyCopier).GetMethod("ConvertValue",
           BindingFlags.Static | BindingFlags.NonPublic);
        method = method.MakeGenericMethod(new[] { tp.PropertyType };
        sourceValue = method.Invoke(null, new[] { sourceValue });
    }
    tp.SetValue(target, sourceValue, null);
    

    We need to use reflection to invoke the generic method with the right type argument, but dynamic typing will use the right conversion operator for you.

    Oh, and one final request: please don’t include my name anywhere near this code, whether it’s in comments, commit logs. Aargh.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following bash code, which is copied and pasted from bash cookbook
I have the following code which i copied from here : /*************************************************************************** * _
So I have the following code which I pretty much copied from here .
I have the following HTML code, which essentially copies a textarea box, including its
I'm trying to use opengl in C#. I have following code which fails with
I have following Code Block Which I tried to optimize in the Optimized section
I have the following code which works just fine when the method is POST,
I have the following code which works fine. However, I only want to return
I have the following code which should put programs startable in Bash. if [
I have the following code which reads in the follow file, append a \r\n

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.