Alice
Alice

Reputation: 183

How do I return type dynamically using List<T>

I've got some WebApi controller and I want to get data from it. I've got various kinds of DTOs and I want to have a function that handles them all. Is there a way to do it?

I want to achieve something like this:

  public dynamic GetData(string ControllersName, dynamic DTOType)
        {         
            string Url = Settings.baseURLAddress + ControllersName;
            var request = (HttpWebRequest)HttpWebRequest.Create(Url);

                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<DTOType>));
                var response = (List<DTOType>)serializer.ReadObject(request.GetResponse().GetResponseStream());
                return response;
        }

Upvotes: 0

Views: 60

Answers (2)

TheGeneral
TheGeneral

Reputation: 81573

You could you generics

public List<T> GetData<T>(string ControllersName)
{         
     string Url = Settings.baseURLAddress + ControllersName;
     var request = (HttpWebRequest)HttpWebRequest.Create(Url);

     DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<T>));
     return (List<T>)serializer.ReadObject(request.GetResponse().GetResponseStream());
}

Usage

var myList = GetData<SomeType>(someName);


Further Reading

Generics (C# Programming Guide)

Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.

Upvotes: 1

Mihail Stancescu
Mihail Stancescu

Reputation: 4138

Have you tried using generics?

public List<T> GetData<T>(string ControllersName, T DTOType)
{         
     string Url = Settings.baseURLAddress + ControllersName;
     var request = (HttpWebRequest)HttpWebRequest.Create(Url);

     DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<T>));
     var response = (List<T>)serializer.ReadObject(request.GetResponse().GetResponseStream());
     return response;
}

Upvotes: 4

Related Questions