Generics and return types

  • Thread starter Thread starter andyblum
  • Start date Start date
A

andyblum

AM I missing something? How can I create a method that returns a
generic data type without making a formal declaration. For Example:


public List<> getData
{


}


I want my function to be able to return any data type that a caller
wants. I do not care what datatype they invoke with the list when
calling me. Ideally, I would then want to be able to inspect what
datatype the list is based on and throw an exception if it is not a
..Net standard datatype. I know this is not compilable is there any
other way to do this?
 
A generic method:
public List<T> GetData<T>() {}

Yes, that's the solution to this problem. In addition, once you have a generic
method, you can inspect the type by using typeof() on it to get a System.Type:

public List<T> GetData<T>()
{
Type type = typeof(T);
// do something with Type.
}

However, you might check to see if the existing generic constraints are expressive
enough for your purposes. That way, you don't have to add runtime checks
and can continue to enjoy the compile-time type safety that generics provide.

Best Regards,
Dustin Campbell
Developer Express Inc
 
Back
Top