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 ?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With