1

I tried this code to copy values from another object a deep clone but it doesnt seem to like nullable properties and I cannot figure out why

public static TConvert ConvertTo<TConvert>(this object entity) where TConvert : new()
{
   var convertProperties = TypeDescriptor.GetProperties(typeof(TConvert)).Cast<PropertyDescriptor>();
   var entityProperties = TypeDescriptor.GetProperties(entity).Cast<PropertyDescriptor>();

   var convert = new TConvert();

   foreach (var entityProperty in entityProperties)
   {
       var property = entityProperty;
       var convertProperty = convertProperties.FirstOrDefault(prop => prop.Name == property.Name);
           
       if (convertProperty != null)
       {
           convertProperty.SetValue(convert, 
           Convert.ChangeType(entityProperty.GetValue(entity), 
           convertProperty.PropertyType));                   }
       }
        return convert;
}

I please a try catch around it and it brought me to this property which does exist in both models.

public int? PullUpHolds { get; set; }

How would I modify the above to take that into account I tried removing the if statment but that still caused a exception on the clone.

My Usuage is

private async void btnEndSession_Clicked(object sender, EventArgs e) 
 {
    var item = dgWeightLifting.SelectedItem as WeightLifting;
    if(item != null)
    {
      var removePlayer= await DisplayAlert(Constants.AppName, 
      $"This will remove the player {item.Players.FullName} 
      from the weight lifting screen. We will make a final 
      record for this session in work out history proceed", 
      "OK", "Cancel");
      if (removePlayer)
      {
                var test =item.ConvertTo<Workout>();
      }
   }
}
c-sharp-and-swiftui-devni
  • 3,743
  • 4
  • 39
  • 100
  • 1
    If you are not interested in private properties then you should take a look at json serialize and deserialize. Just two lines – Steve Apr 16 '22 at 20:50
  • 1
    Good idea just re serlize to the other object why didnt i think of that am doing that anyway in my api thanks steve as always lad – c-sharp-and-swiftui-devni Apr 16 '22 at 20:51
  • Close related to [this question](https://stackoverflow.com/questions/5713556/copy-object-to-object-with-automapper) – Cleptus Apr 16 '22 at 20:52
  • @Steve what about the dynamic properties like FullName will this take that into account as well when cloning – c-sharp-and-swiftui-devni Apr 16 '22 at 20:55
  • Not sure what do you mean. Json serializer will take all the public properties and build a json string that you can immediately deserialize. This question has the example https://stackoverflow.com/questions/78536/deep-cloning-objects – Steve Apr 16 '22 at 20:56

0 Answers0