0

Suppose I have following kind of code:

foreach(var x in Mylist)  //MyList is EntitySet
{
//......
}

I want to know the type of x and create another new instance of same type and the clone x to new instance like:

foreach(var x in Mylist)
{
  string tyoename = typeof(x).AssemblyQualifiedName; //get the type of x, but i got error here
  //create instance of the type
  //clone x data to new instance 
}

MyList is dynamic data, x could be different type when Mylist changed. How to implement this request?

KentZhou
  • 24,805
  • 41
  • 134
  • 200
  • 1
    Could be similar to the discussion here about cloning objects: http://stackoverflow.com/questions/78536/cloning-objects-in-c-sharp – Mike Parkhill Apr 02 '12 at 20:04
  • This isn't possible in the general case, you are going to have to make some assumptions about the objects that you are trying to clone... surfen's answer is pretty good as long as you assume your objects are serializable. – Yaur Apr 02 '12 at 21:06

2 Answers2

3

I use the following extension method:

public static class CloningExtensions
{
    public static T Clone<T>(this T source)
    {
//            var dcs = new DataContractSerializer(typeof(T), null, int.MaxValue, false, true, null);
        var dcs = new System.Runtime.Serialization
          .DataContractSerializer(typeof(T));
        using (var ms = new System.IO.MemoryStream())
        {
            dcs.WriteObject(ms, source);
            ms.Seek(0, System.IO.SeekOrigin.Begin);
            return (T)dcs.ReadObject(ms);
        }
    }
}

Like this:

foreach(var x in Mylist)
{
    var y = x.Clone();
}

But you have to be careful with classes that do not support serialization because this method doesn't call the constructor and doesn't initialize private fields. I workaround it using OnDeserializing/OnDeserialized method (defined on every type that I need to be able to clone)

[OnDeserialized]
private void OnDeserialized(StreamingContext c)
{
    Init();
}
surfen
  • 4,644
  • 3
  • 34
  • 46
0

you can create objects of class dynamically like this.

T ReturnObject<T>(T x)
{
Type typeDynamic=x.GetType();
Type[] argTypes = new Type[] { };
ConstructorInfo cInfo = typeDynamic.GetConstructor(argTypes);
T instacneOfClass = (T)cInfo.Invoke(null);
return instacneOfClass;
}
Vetrivel mp
  • 1,214
  • 1
  • 14
  • 29