1

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;
}
Zachary Scott
  • 20,968
  • 35
  • 123
  • 205

4 Answers4

3

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

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

Matthias Meid
  • 12,455
  • 7
  • 45
  • 79
1

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

TomTom
  • 61,059
  • 10
  • 88
  • 148
0

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
  • 15,744
  • 7
  • 51
  • 73