Created
December 31, 2020 02:59
-
-
Save pedrovasconcellos/e271f9ca2ccb6ce1aa51839e55786bc7 to your computer and use it in GitHub Desktop.
ObjectExtension with CopyObject and CopyPropertiesTo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
using System.Collections.Generic; | |
using System.Runtime.Serialization.Formatters.Binary; | |
using System.Linq; | |
namespace Vasconcellos.Extensions | |
{ | |
public static class ObjectExtension | |
{ | |
/// <summary> | |
/// Put in the class to be copied the attribute [Serializable]. | |
/// </summary> | |
public static T CopyObject<T>(this T objSource) | |
{ | |
using (MemoryStream stream = new MemoryStream()) | |
{ | |
BinaryFormatter formatter = new BinaryFormatter(); | |
formatter.Serialize(stream, objSource); | |
stream.Position = 0; | |
return (T)formatter.Deserialize(stream); | |
} | |
} | |
public static IList<T> ObjectToList<T>(this T objSource) => new List<T>() { objSource }; | |
public static void CopyPropertiesTo<T, TU>(T source, TU dest) | |
{ | |
var sourceProps = typeof(T).GetProperties().Where(x => x.CanRead).ToList(); | |
var destProps = typeof(TU).GetProperties().Where(x => x.CanWrite).ToList(); | |
foreach (var sourceProp in sourceProps) | |
{ | |
if (destProps.Any(x => x.Name == sourceProp.Name)) | |
{ | |
var p = destProps.First(x => x.Name == sourceProp.Name); | |
if (p.CanWrite) | |
{ | |
p.SetValue(dest, sourceProp.GetValue(source, null), null); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment