Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Pass Different Objects to same Function in C#

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 ?

like image 659
neildt Avatar asked Aug 09 '13 12:08

neildt


People also ask

Can we pass objects as function arguments?

To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables. Syntax: function_name(object_name); Example: In this Example there is a class which has an integer variable 'a' and a function 'add' which takes an object as argument.

Can we pass objects by reference?

A mutable object's value can be changed when it is passed to a method. An immutable object's value cannot be changed, even if it is passed a new value. “Passing by value” refers to passing a copy of the value. “Passing by reference” refers to passing the real reference of the variable in memory.

What are the two ways to passed objects as function argument?

Objects as Function Arguments in c++ The objects of a class can be passed as arguments to member functions as well as nonmember functions either by value or by reference.


1 Answers

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.

like image 128
Jeroen van Langen Avatar answered Nov 01 '22 13:11

Jeroen van Langen