Reputation: 5362
I have 10 different classes, but below are two for the purpose of this question :
public class Car
{
public int CarId {get;set;}
public string Name {get;set;}
}
public class Lorry
{
public int LorryId {get;set;}
public string Name {get;set;}
}
Now I have a function like
public static object MyFunction(object oObject, string sJson)
{
//do something with the object like below
List<oObject> oTempObject= new List<oObject>();
oTempObject = JsonConvert.DeserializeObject<List<oObject>>(sJson);
return oTempObject;
}
What I'm wanting to do is pass the object I create like (oCar) below to the function.
Car oCar = new Car();
My question is how can I pass a object of a different type to the same function ?
Upvotes: 5
Views: 8263
Reputation: 22083
Using generic methods will solve the trick:
public static List<T> MyFunction<T>(string sJson)
{
//do something with the object like below
return (List<T>)JsonConvert.DeserializeObject<List<T>>(sJson);
}
Usage:
List<Car> cars = MyFunction<Car>(sJson);
or
List<Lorry> cars = MyFunction<Lorry>(sJson);
Update (thanks to Matthew for noticing the type behind the method name), btw: this is not needed when a parameter is type T.
Upvotes: 10