I need to find a way to make a copy of an object of type Type
. I have some code that make copy of object and lots of those object have properties of type Type
. I cannot simply do an equal otherwise the reference will be the same and down the line a couple of these copies objects will have these property modified but it must not update the other ones so it has to be a new value.
So here's a very basic example class and behavior
public class A
{
public int Quantity { get; set; } = 0;
public Type ConnectionType { get; set; } = null;
public A Copy()
{
var copy = new A();
copy.Quantity = Quantity;
copy.ConnectionType = ???
}
}
My idea was simple, I told myself "Hey let's just hack this quickly and instantiate an object of that type and grab it's GetType()"
So I tried this :
public A Copy()
{
var copy = new A();
copy.Quantity = Quantity;
var copyType = Activator.CreateInstance(ConnectionType).GetType();
copy.ConnectionType = copyType;
}
Don't get me wrong this works for a very handful of classes. The problem is that the different Type that is passed in that property do not all have default constructor. The class are also not all developed internally and are changing once or twice a week.
Is there any way to copy the Type
class without resorting on Activator.CreateInstance
.
Obviously this is a very small sample. In reality I have many properties of type Type
in thousands of object and the real code actually use a lot of reflection and this particular property execute such code if the PropertyInfo.PropertyType
is Type
.
CodePudding user response:
There will always be only one Type
for each class, so you can safely assign it.
For two objects x and y that have identical runtime types, Object.ReferenceEquals(x.GetType(),y.GetType()) returns true.
So there is no way that two Type
instances could exist for any given class, there will always be only one (ReferenceEquals
cannot be overriden)
In your case you could just do:
copy.ConnectionType = ConnectionType;
Full example:
public class A
{
public int Quantity { get; set; } = 0;
public Type ConnectionType { get; set; } = null;
public A Copy()
{
var copy = new A();
copy.Quantity = Quantity;
copy.ConnectionType = ConnectionType;
return copy;
}
}
CodePudding user response:
Activator.CreateInstance(ConnectionType).GetType()
should return the same instance of Type
. From the docs:
For two objects
x
andy
that have identical runtime types,Object.ReferenceEquals(x.GetType(),y.GetType())
returns true.
So there is no point to use Activator.CreateInstance
approach - simple shallow copying will have the same effect.
CodePudding user response:
Type
objects are immutable. You can treat immutable types (like string
) as if they were value types. Therefore, making a clone is not necessary.
Also, you cannot create and initialize Type
objects yourself, nor can you clone them.