Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# returning different types from function

I have written a following code which basically performs a JSON request towards my server:

   var client = new RestClient("mysite.com");
            var request = new RestRequest(Method.POST);
            request.RequestFormat = DataFormat.Json;
            request.AddParameter("application/x-www-form-urlencoded", /*params here...*/ ,ParameterType.RequestBody);
            return JsonConvert.DeserializeObject<MyCustomType>(client.Execute(request).Content);

Please note the last line of code:

return JsonConvert.DeserializeObject<MyCustomType>(client.Execute(request).Content);

Where i de-serialize the returned JSON from server to a previously class structures in my application.

Now the problem is that server can either return error response or success response, and for each of those cases i need a different class structure so that I can map them to C# class objects...

So I thought something like this would do:

public object PerformMyAwesomeRequest(string myToken) 
{
 var response =client.Execute(request).Content;
 var statusCode = FetchStatusCode(response);
if(statusCode == 0)//signaling the response returned error
{
return JsonConvert.DeserializeObject<ErrorMessageCustomType>(response);
}
else{
return JsonConvert.DeserializeObject<MyCustomType>(response);
}
}

So this way it doesn't gives me any errors... But the problem here is that these objects now only exist in runtime, and I cannot determine which type server returned in my .NET MVC Action which looks like this:

public ActionResult SomeActon(){
var response = PerformMyAwesomeRequest("mytokenhere...");
//response object is assigned a corresponding type only at runtime...
}

So my question here is:

  • What type can I return from my function that performs the http request towards the server so that I can know which type was returned from the function directly at code and not only in runtime ?
like image 786
User987 Avatar asked Jun 18 '26 09:06

User987


1 Answers

The only way for a method to return objects of different types is to return their common base type. However, you already discovered that the common superclass of object is of no help to you, so let's consider alternatives to returning an object in the first place:

  • Return on success and throw on error - this approach lets you return MyCustomType, and throw some exception wrapping ErrorMessageCustomType. Since one object is returned, and the other is thrown, there is no requirement for the types to be related.
  • Return a combined object - make class with members for each type you plan to return, and set only one of them in the PerformMyAwesomeRequest method. This is not as good, because it requires a chain of if-elses in the caller.
  • Accept an out parameter for the error - if the request is unsuccessful, return null, and set the out parameter to ErrorMessageCustomType.
  • Accept callback delegates - rather than returning a value, accept two delegates, one for success, and one for the failure scenario, i.e. void PerformMyAwesomeRequest(string tok, Action<MyCustomType> onSuccess, Action<ErrorMessageCustomType> onError).

The last approach can be used like this:

PerformMyAwesomeRequest(
    myToken
,   data => {
        Console.WriteLine("Received data: {0}", data);
    }
,   error => {
        Console.WriteLine("Received error: {0}", error);
    }
);

The method can be implemented like this:

public void PerformMyAwesomeRequest(string myToken, Action<MyCustomType> onSuccess, Action<ErrorMessageCustomType> onError) {
    var response = client.Execute(request).Content;
    var statusCode = FetchStatusCode(response);
    if (statusCode != 0) {
        onSuccess(JsonConvert.DeserializeObject<MyCustomType>(response));
    } else {
        onError(JsonConvert.DeserializeObject<ErrorMessageCustomType>(response));
    }
}
like image 188
Sergey Kalinichenko Avatar answered Jun 20 '26 21:06

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!