vr552
vr552

Reputation: 301

How to change the same properties of different objects in one method?

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.

Upvotes: 1

Views: 332

Answers (1)

Johnathan Barclay
Johnathan Barclay

Reputation: 20353

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

Upvotes: 2

Related Questions