5

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 ?

neildt
  • 5,101
  • 10
  • 56
  • 107
  • 2
    You should read this as well - http://stackoverflow.com/questions/111933/why-shouldnt-i-use-hungarian-notation – Yuck Aug 09 '13 at 12:23
  • 1
    Everywhere you're using `oObject` in that function, you're using it like a type. Shouldn't this just be a generic method with a type argument instead of `oObject`? – Damien_The_Unbeliever Aug 09 '13 at 12:24
  • Why dont you use Generic Something like `public static object MyFunction(T oObject, string sJson)` – Nilesh Aug 09 '13 at 12:26
  • @Damien_The_Unbeliever, I think he's just adding that to illustrate his intentions. – Smeegs Aug 09 '13 at 12:29

1 Answers1

10

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.

Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57