Recently I was in need of a method to copy an object and pass it to a method which alters the data. Since a class is passed by reference this would alter the class in the caller which I don't want.
So, I wrote a generic extension method which does the trick. Yet i'm unsure if this is a good solution to my problem. I would like to use reflection to achieve the goal. I can't use ICloneable
and I would like to avoid serializing and deserializing the class. I have also looked into making the class
a struct
but will refrain from this since the classes can be way larger than 16 bytes and don't really suit the basic guidelines of when to use a struct
.
Here is my extension method:
public static T CreateNonReferencedObject<T>(this T obj)
{
var tObj = (T)Activator.CreateInstance(typeof(T));
if (obj == null) return tObj;
var properties = obj.GetType().GetProperties();
foreach (var property in properties)
{
var value = property.GetValue(obj);
tObj.GetType().GetProperty(property.Name).SetValue(tObj, value);
}
return tObj;
}
1 Answer 1
After a deeper dive as to why I exactly made this function I have found out that I made this extension method to remove the reference from an entity I Get()
with Entityframework facepalm. I have rewritten the code to .AsNoTracking()
instead so the code actually makes sense. The CreateNonReferencedObject()
method is now unnecessary.
ref
keyword in a method signature. \$\endgroup\$struct
is a value type, so there is noreference
to a struct. ... RE: "16 bytes". I know that's quoted from microsoft, but how in the wide world of compilation can I know what my High Level Language will compile to without trial and error? If this nugget of esoteric 4-bit CPU nostalgia is about taking up stack memory, the computer will let me know if there is StackOverflow. Hey, moderators! I'm supposed to get 15 points for using "StackOverflow", validly, in a sentence. \$\endgroup\$