It's not quite clear of the exact function of Duplicate(), but the following example works when your type you want to pass in to Duplicate() is a class or an int.
Essentially, don't pass in a type, pass in an example object. This test method illustrates the call (two tests in one method)
[TestMethod]
public void TestMethod1()
{
var myObject = new AnObject { AString = "someString" };
var myOtherObject = new AnotherObject();
var newObject = myObject.Duplicate(myOtherObject);
Assert.IsTrue(newObject.AString=="someString");
var newObject2 = myObject.Duplicate(1);
Assert.IsTrue(newObject2 is Int32);
}
The Duplicate() method has a type parameter linked to the example object, but does not need to be called with the type given as a parameter, it infers it from the example object.
Here is the class with a Duplicate() method:
public class AnObject
{
public string AString { get; set; }
public T Duplicate<T>(T exampleObject)
where T: new()
{
var newInstance = (T)Activator.CreateInstance<T>();
// do some stuff here to newInstance based on this AnObject
if (typeof (T) == typeof (AnotherObject))
{
var another = newInstance as AnotherObject;
if(another!=null)
another.AString = this.AString;
}
return newInstance;
}
}
To complete the picture, this is the AnotherObject class.
public class AnotherObject
{
public string AString { get; set; }
}
This code may have some problems inside the Duplicate() method when the type passed in is a value type like int. It depends on what you want Duplicate() to do with the int (you may have to be pass it in as a nullable int).
It works well for reference types (classes).