views:

49

answers:

4

This code returns a variable set of fields and I want to return a strongly typed <E>:

public IList<E> Get(Expression<Func<E, object>> selectLambda == null)
{
    if (selectLambda == null)
        selectLambda = p => p;
    var partialSet = DC.CreateQuery<E>("[" + typeof(E).Name + "]");
    foreach ( var record in partialSet)
    {
        var tempEntity = new E();  // This is the error
        MapIt( record, tempContract);
        result.Add(tempContract);
    }
    return result;
}
+1  A: 

E must support the new () definition as per generic constraint (i.e. E must be ": new ()")

TomTom
+2  A: 

The simplest way is to add a constraint:

public IList<E> Get(Expression<Func<E, object>> selectLambda == null)
    where E : new()

Then the rest of your code will compile :)

If you can't use constraints there (e.g. because they would propagate all over the place) but you happen to know that it will work at execution time, you could use:

var tempEntity = Activator.CreateInstance<E>();
Jon Skeet
What if you have public class MyClass<E> : IClass<E> : where E : EntityObject, then later have your code. The compiler error is "Constraints are not allowed on non-generic declarations"
Dr. Zim
That's a very nice answer. TYVM
Dr. Zim
@Dr. Zim: I assume you've sorted out your first error now then? (Basically you've got an extra colon).
Jon Skeet
+1  A: 

You need a constraint for E:

public IList<E> Get() where E : new()

This way you make sure E does have a parameterless constructor.

Cheers Matthias

Mudu
A: 

If E does not have empty constructor you can pass delegate to your method which you can use to create E. In this case caller of the method would be responsible for passing proper delegate.

public IList<E> Get(Expression<Func<E, object>> selectLambda == null, Func<E> creator)
{
    // ...
    var tempEntity = creator();  
    // ...
}
Andrew Bezzub