Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Generic Method for Accepting Type Object and return a new Object of Type

Tags:

c#

.net

generics

I want to create a generic method for my Service Request and Response with RestSharp. I want to pass resource url and Object Name of any class and hope to get the response of the same object type which I passed.

I am not finding a way to run this code and I know its not the perfect way, but I will be glad if anyone direct me to correct path e.g.

class Employee
{
    Employee em = new Employee();
    RequestClass CreateRequest = new Request();
    public Employee GetAllEmployee()
    {
        return RequestClass.MyRequest("http://get-all-employee",em);
    }
}

class RequestClass
{
    public Type MyRequest(string resource, Type objectName)
    {
        var client = new RestClient("http://Service-url.com");
        var request = new RestRequest(resource, Method.GET);
        var response = client.Execute(request);
        var result = response.Content;

        Type ClassName = objectName.GetType();
        Object myobject = Activator.CreateInstance(ClassName);

        JsonDeserializer jsonDeserializer = new JsonDeserializer();
        myobject = jsonDeserializer.Deserialize<Type ClassName>(response);

        return (Type)myobject;
    }
}       
like image 213
Muhammad Arslan Jamshaid Avatar asked Dec 01 '25 03:12

Muhammad Arslan Jamshaid


1 Answers

Use a generic type parameter with a new() constraint:

public T MyRequest<T>(string resource) where T : new()
{
    var client = new RestClient("http://Service-url.com");
    var request = new RestRequest(resource, Method.GET);
    var response = client.Execute(request);

    JsonDeserializer jsonDeserializer = new JsonDeserializer();
    return jsonDeserializer.Deserialize<T>(response);
}

And then use it like this:

public Employee GetAllEmployee()
{
    var requestClass = new RequestClass();
    return requestClass.MyRequest<Employee>("http://get-all-employee");
}
like image 54
Yuval Itzchakov Avatar answered Dec 02 '25 16:12

Yuval Itzchakov