0

I have a generic business object collection class which contains some business objects:

public abstract class BusinessObjectCollection<T> : ICollection<T> 
    where T : BusinessObject

I want to write a method on my Collection class that returns the type T and a method that returns a newly-instantiated object of type T.

In C++, this would be where you simply declare a typedef value_type T; and use BusinessObjectCollection::value_type but I can't find an equivalent in C#.

Any suggestions?

EDIT: One close parallel to the typedef I was thinking of is the method:

Type GetGenericParameter() { 
    return typeof(T); 
}
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Scott Stafford
  • 43,764
  • 28
  • 129
  • 177

2 Answers2

10

Try something like this:

public abstract class BusinessObjectCollection<T> : ICollection<T> 
    where T : BusinessObject, new()
{
    // Here is a method that returns an instance
    // of type "T"
    public T GetT()
    {
        // And as long as you have the "new()" constraint above
        // the compiler will allow you to create instances of
        // "T" like this
        return new T();
    }
}

In C# you can use the type parameter (i.e. T) as you would any other type in your code - there is nothing extra you need to do.

In order to be able to create instances of T (without using reflection) you must constrain the type parameter with new() which will guarantee that any type arguments contain a parameterless constructor.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
  • Actually this does use reflection too. C# emits a call to Activator.CreateInstance. – Josh Feb 24 '10 at 22:54
  • That is very true that the *compiler* emits calls to `Activator.CreateInstance`. I was simply stating that the OP would not have to use the reflection API directly, not that reflection was not used at all under the covers. – Andrew Hare Feb 25 '10 at 00:34
1

With regards to finding a type:

If you need to know what the type of T is, you can simply use typeof(T).

Community
  • 1
  • 1
Mark Simpson
  • 23,245
  • 2
  • 44
  • 44