mercredi 8 juin 2016

Simplest way to Convert an existing Method to generic object Type

Let's assume I have an existing method which ALWAYS returns a variable of type OldClassType

//Takes 1 parameter p1
//Returns a variable of type OldClassType, after doing a bunch of logic.
protected OldClassType MyMethod(int32 p1)
{
   OldClassType myVar = new OldClassType();
   myVar.name = "Hello";
   myVar.age = "36";

   return myVar;
}

Now, I have a NewClassType which has exactly the same properties as OldClassType but is of a different namespace. I need to convert the same method (MyMethod) so that instead of ALWAYS returning OldClassType, it should return a variable of type either OldClassType or NewClassType - based on a newly added parameter useNewType

So something like :

//Takes 2 parameter: p1 and useNewType - which determines when to use the NewClassType or default to the OldClassType
//Returns a variable of type object, after doing a bunch of logic. I'll modify the Call to this new modified method to cast the object to the appropriate Type (OldClassType/NewClassType)
protected object MyMethod(int32 p1, bool useNewType)
{  
   object myVar = new object();
   myVar.name = "Hello"; // Do I use PropertyInfo and then set value?
   myVar.age = "36";

   return myVar; 
}





Aucun commentaire:

Enregistrer un commentaire