1

I have a method that performs the same function on different objects passed in:

public ??? DoThings(??? inputObject)
{
  //do things

  if(condition)
    inputObject.Status = "error";
}

Objects are of the following class:

public class BaseResponse<T>
{
  public string Status { get; set; }
  public T Data { get; set; }

  public static BaseResponse<T> FromJson(string data)
  {
    return JsonConvert.DeserializeObject<BaseResponse<T>>(data, JsonHelper.JsonSettings);
  }
}

At the end of the method I may need to change the object's Status to an error. How can this be achieved? I have tried to pass in object inputObject. but that of course doesn't work.

vr552
  • 181
  • 1
  • 10
  • 1
    Like `public void DoThings(List> manyInputObjects)`? – Thomas Weller Jul 12 '21 at 13:31
  • And likely you have a list of different T's and you want to invoke DoThings on each item, but unfortunately you don't know which item resolves to which T ??? – lidqy Jul 12 '21 at 13:57

1 Answers1

2

Make the method generic:

public void DoThings<T>(BaseResponse<T> inputObject)
{
    // do things

    if (condition) inputObject.Status = "error";
}

Then you can pass any BaseResponse<T> object:

var baseResponse = BaseResponse<SomeDataType>.FromJson(jsonString);
DoThings(baseResponse); // T can be inferred from baseResponse
Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35
  • Depends on the context of the call site whether or not T can be inferred. If you deal with a list of objects of mixed types and for ease used an ArrayList or List to collect them, T will not be so easily resolved. It could be easier to add an non-generic `interface IStatus { string Status {get;set;} }` to BaseResponse. And type the formal parameter of DoThings by that interface. Assuming you don't need the typing to BaseObject or T in the code not shown....As usually - depends on the context... – lidqy Jul 12 '21 at 13:55
  • @lidqy If `ArrayList` or `List` are used, you wouldn't be able to call `DoThings` at all (without casting). – Johnathan Barclay Jul 12 '21 at 13:59
  • Yes but since he said "I tried to use 'object' but it didn't work" and also "I have a method that performs the same function on **different** **objects** **passed** **in**" there seems to be a problem to simply type DoThings param as 'BaseResponse'. Most of the time this happens when a generic collection is mixed and the T of each item is not known or its not so easy to get it compiled. – lidqy Jul 12 '21 at 14:06
  • @lidqy OP tried `object` as the argument type, but `object` doesn't have a `Status` property. – Johnathan Barclay Jul 12 '21 at 14:08