Monthly Archives: May 2015

How to invoke a method that needs a generic type parameter through reflection

problem:

How to invoke a method that needs a generic type parameter through reflection

answer:

  1. Use the “Getinfo” of that type and pass it the a parameter of the name of the method you want to call.
  2. Convert the method that you assigned to a variable to a generic method using “MakeGenericMethod”
  3. Invoke the method with the parameters needed for that method
var person = new Person();
var personType = typeof(Person);
var methodInfo = personType.GetMethod('Speak');
methodInfo = methodInfo.MakeGenericMethod(typeof(DateTime));
methodInfo.Invoke(person, null);

//NOTE 
public void Speak<T>()
{
    //Name is a public property on the Person class
    Console.Write(typeof(T).Name);
}

How to create a dynamic collection in C#

problem:

I need to instantiate many collections. How can I do this dynamically with reflection?

answer:

Use the typeof to get the type of your collection and what kind of collection it will become. Pass those as parameters to a custom method to convert your parameters into a collection using “MakeGenericType” for your collection type and pass in the parameter of what object the collection should contain. Now use C#’s Activator class to create an instance of your collection and return it.

class Program
{
    static void Main(string[], args)
    {
        var myList = CreateCollection(typeof(List<>), typeof(Employee));
        // do more stuff here ...
    }

    private static object CreateCollection(Type collectionType, Type iteType)
    {
        var closedType = collectionType.MakeGenericType(itemType);
        return Activator.CreateInstance(closedType);
    }
}

How to capture a query string in a RESTful Get Request

problem:

I need to access the query parameter in the RESTful GET URL.

answer:

We overwrite our current GET method with another GET method that accepts a parameter. This parameter will be your query string. Then use LINQ to process your Enumerable object and return a filtered collection.

public IEnumerable<Product> Get(string queryString) { 
  var repository = new Repository(); 
  var products = repository.Retrieve(); 
  return products.Where(p => p.ProductId.Contains(queryString)); 
}