tags:

views:

59

answers:

4

I have various classes that implements IActiveRecord.

I want to have a method where I pass in a newly created class and assign ActiveRecord to the type of the class passed in.

I have tried the below but it does not compile for some reason.

Any ideas?

private void AddRecord<T>() where T : class, new()
        {

            IActiveRecord ActiveRecord = (IActiveRecord)T;
        }
A: 

I think you want to restrict your method by using the following:

private void AddRecord<T>() where T : IActiveRecord, new()

Otherwise, your question might not be clear to me.

Webleeuw
Thanks for whoever downvoted me, but can you explain why my answer is bad?
Webleeuw
+4  A: 

Your question is unclear, but if I understand correctly what you are trying to do, you just need to add the constraint where T : IActiveRecord. Then you can say

void AddRecord<T>() where T : IActiveRecord, new() { 
    IActiveRecord activeRecord = new T();
    // more stuff
}

Regarding your line

IActiveRecord ActiveRecord = (IActiveRecord)T;

this is not legal. T is a type parameter, not an expression that you can cast.

Jason
Even though new is passed in as new()
Jon
+2  A: 

In the method you're displaying, you do not pass in an instance of a certain type ? I do not really understand what you're trying to achieve.

Do you want to do this:

private void AddRecord<T>() where T : IActiveRecord, new()
{
    IActiveRecord a = new T();
}

?

Frederik Gheysels
+2  A: 

Looks like you want to constrain the generic type to be of type IActiveRecord, then you don't need the cast:

private void AddRecord<T>() where T : IActiveRecord, new()
{
    IActiveRecord a = new T();
}
Oded