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

  • Home
  • SEARCH
  • 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 7813041
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T04:43:08+00:00 2026-06-02T04:43:08+00:00

Possible Duplicate: Cloning objects in C# What I want to do is copy the

  • 0

Possible Duplicate:
Cloning objects in C#

What I want to do is copy the values in a class from one object to another. Shallow Copy is just fine. However, I do not want to lose the reference that object has to the list/array/ienumerable. Also, I don’t want to want to do this either:

public static void EditEvent(EventModel editEvent)
{
    EventModel changingEvent = EventRepository.getEvent(editEvent.EventID);
    changingEvent.Subject = editEvent.Subject;
    changingEvent.EventDate = editEvent.EventDate;
    changingEvent.EventDesc = editEvent.EventDesc;
    changingEvent.DayCode = editEvent.DayCode;
}

But rather:

public static void EditEvent(EventModel editEvent)
{
    EventModel changingEvent = EventRepository.getEvent(editEvent.EventID);
    changingEvent.CopyFrom(editEvent);
    //or
    editEvent.CopyTo(changingEvent);
}
  • 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-02T04:43:10+00:00Added an answer on June 2, 2026 at 4:43 am

    This is code I wrote today. It passes simple tests. I’m thinking you can use it to get started.

    Here is the test:

        /// <summary>
        ///A test for MapProperties
        ///</summary>
        public void MapPropertiesTestHelper<S, T>(S source, T target1, bool failIfNotMatched)
        {
            Cake.Common.Mapper<S, T> target = new Cake.Common.Mapper<S, T>();
            target.MapProperties(source, target1, failIfNotMatched);
        }
    
        [TestMethod()]
        public void MapPropertiesTest()
        {
            var source = new Source {
                OneTwo = 10,
                ThreeFour = "foo"
            };
    
            var target = new Target {
                OneTwo = 10,
                ThreeFour = "bar"
            };
    
            MapPropertiesTestHelper<Source, Target>(source, target, true);
    
            Assert.AreEqual(source.OneTwo, target.OneTwo);
            Assert.AreEqual(source.ThreeFour, target.ThreeFour);
            Assert.AreEqual(source.five_six, target.FiveSix);
        }
    
        public class Source
        {
            public int OneTwo { get; set; }
            public string ThreeFour { get; set; }
            public bool five_six { get; set; }
        }
    
        public class Target
        {
            public int OneTwo { get; set; }
            public string ThreeFour { get; set; }
            public bool FiveSix { get; set; }
        }
    

    And here is the code:

    public class MapperItem
    {
        public MapperItem(MemberInfo member, object o)
        {
            this.Member = member;
            this.Object = o;
        }
    
        public MemberInfo Member 
        { 
            get; 
            set; 
        }
    
        public object Object
        {
            get;
            set;
        }
    
        public Type Type
        {
            get
            {
                return this.Member.UnderlyingType();
            }
        }
    
        public object Value
        {
            get
            {
                if (this.Member is PropertyInfo)
                {
                    return (this.Member as PropertyInfo).GetValue(this.Object, null);
                }
                else if (this.Member is FieldInfo)
                {
                    return (this.Member as FieldInfo).GetValue(this.Object);
                }
                else
                {
                    throw new Exception("sourceMember must be either PropertyInfo or FieldInfo");
                }
            }
        }
    
        public object Convert(Type targetType)
        {
            object converted = null;
    
            if (this.Value == null)
            {
                return converted;
            }
            else if (targetType.IsAssignableFrom(this.Type))
            {
                converted = this.Value;
            }
            else
            {
                var conversionKey = Tuple.Create(this.Type, targetType);
                if (Conversions.ContainsKey(conversionKey))
                {
                    converted = Conversions[conversionKey](this.Value);
                }
                else
                {
                    throw new Exception(targetType.Name + " is not assignable from " + this.Type.Name);
                }
            }
    
            return converted;
        }
    
        public void Assign(object value)
        {
            if (this.Member is PropertyInfo)
            {
                (this.Member as PropertyInfo).SetValue(this.Object, value, null);
            }
            else if (this.Member is FieldInfo)
            {
                (this.Member as FieldInfo).SetValue(this.Object, value);
            }
            else
            {
                throw new Exception("destinationMember must be either PropertyInfo or FieldInfo");
            }
        }
    
        public static Dictionary<Tuple<Type, Type>, Func<object, object>> Conversions = new Dictionary<Tuple<Type, Type>, Func<object, object>>();
    }
    
    public class Mapper<S, T>
    {
        private List<string> ignoreList = new List<string>();
        public List<string> IgnoreList
        {
            get { return ignoreList; }
            set { ignoreList = value; }
        }
    
        public void MapProperties(S source, T target, bool failIfNotMatched = true)
        {
            foreach (PropertyInfo property in source.GetType()
                                                          .GetProperties()
                                                          .Where(c => !IgnoreList.Contains(c.Name)))
            {
                try
                {
                    var sourceField = new MapperItem(property, source);
                    var targetField = new MapperItem(MatchToTarget(property), target);
                    targetField.Assign(sourceField.Convert(targetField.Type));
                }
                catch (TargetNotMatchedException noMatch)
                {
                    if (failIfNotMatched)
                    {
                        throw noMatch;
                    }
                }
            }
        }
    
        private MemberInfo MatchToTarget(MemberInfo member)
        {
            List<MemberInfo> members = new List<MemberInfo>();
            members.AddRange(typeof(T).GetProperties());
            members.AddRange(typeof(T).GetFields());
    
            var exactMatch = from c in members where c.Name == member.Name select c;
    
            if (exactMatch.FirstOrDefault() != null)
            {
                return exactMatch.First();
            }
    
            var sameAlphaChars = from c in members
                                 where NormalizeName(c.Name) == NormalizeName(member.Name)
                                 select c;
    
            if (sameAlphaChars.FirstOrDefault() != null)
            {
                return sameAlphaChars.First();
            }
    
            throw new TargetNotMatchedException(member, typeof(T));
        }
    
        private static string NormalizeName(string input)
        {
            string normalized = input.Replace("_", "").ToUpper();
            return normalized;
        }
    }
    
    public class TargetNotMatchedException : Exception
    {
        public TargetNotMatchedException(MemberInfo member, Type type)
            : base("no match for member named " + member.Name + " with type named " + type.Name)
        {
            this.Member = member;
            this.Type = type;
        }
        public MemberInfo Member { get; set; }
        public Type Type { get; set; }
    }
    
    public static class ReflectionExtensions
    {
        public static Type UnderlyingType(this MemberInfo member)
        {
            Type type;
            switch (member.MemberType)
            {
                case MemberTypes.Field:
                    type = ((FieldInfo)member).FieldType;
                    break;
                case MemberTypes.Property:
                    type = ((PropertyInfo)member).PropertyType;
                    break;
                case MemberTypes.Event:
                    type = ((EventInfo)member).EventHandlerType;
                    break;
                default:
                    throw new ArgumentException("MemberInfo must be if type FieldInfo, PropertyInfo or EventInfo", "member");
            }
            return Nullable.GetUnderlyingType(type) ?? type;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: What do parentheses surrounding a JavaScript object/function/class declaration mean? What does this
Possible Duplicate: DOMElement cloning and appending: ‘Wrong Document Error’ I would like to copy
Possible Duplicate: declare property as object? class core { public $dbh = new PDO(mysql:dbname=newdbnaem;host=1.1.1.1:1111,
Possible Duplicate: Working with latitude/longitude values in Java Duplicate: Working with latitude/longitude values in
Possible Duplicate: In Linux, how to prevent a background process from being stopped after
Possible Duplicates: Deep copy vs Shallow Copy In Java, what is a shallow copy?
Possible Duplicate: Hibernate: different object with the same identifier value was already associated with
Possible Duplicate: Should one call .close() on HttpServletResponse.getOutputStream()/.getWriter()? Am I responsible for closing the
Possible Duplicate: Extracting dollar amounts from existing sql data? I have a column in
Possible Duplicate: Removing an activity from the history stack Suppose I have three activities

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.