1

I have a class implementing an interface, which has a multi-parameter constructor, and a static sorted collection. This class is a Base Class which has many inherited classes.

internal class SCO : IVotable
{
    public SCO(SPListItem item, List<Vote> votes)
    {
        //Initialize Object
    }

    public static List<T> SortedCollection<T>(SPListItemCollection items, ListSortType sortType, List<Vote> votes) where T : IVotable
    {
        var returnlist = new List<T>();
        Type genericType = typeof(T);
        for (int i = 0; i < items.Count; i++) { returnlist.Add((T)Activator.CreateInstance(genericType, new object[] { items[i], votes })); }
        switch (sortType)
        {
            case ListSortType.Hot:
                returnlist.Sort((p1, p2) => p2.HotScore.CompareTo(p1.HotScore));
                break;
            case ListSortType.Top:
                returnlist.Sort((p1, p2) => p2.VoteTotal.CompareTo(p1.VoteTotal));
                break;
            case ListSortType.Recent:
                returnlist.Sort((p1, p2) => p2.CreatedDate.CompareTo(p1.CreatedDate));
                break;
        }
        return returnlist;
    }
}

This allows me to do the following with any Child Class:

List<ChildClass> sortedClassList = ChildClass.SortedCollection<ChildClass>(listItems, sortType, votes);

My current reliance on Activator.CreateInstance worries me, as this is about 100 times slower than using Emit IL directly. I've been reading a few articles about Emit IL, and it seems fantastic for this solution.

I cannot seem to get it to work, however. When I try to instantiate ILGenerator gen = it tells me "Cannot access non-static field 'method' in static context"

My class isn't static, neither are my constructors, and the static list show below isn't interacting with Emit yet. How do I make this work?

Code thus far:

internal class SCO : IVotable
{
    //Properties emittied
    static ConstructorInfo ctor = typeof(SCO).GetConstructors()[1];
    delegate SCO SCOCtor(SPListItem item, List<Vote> votes);
    static SCOCtor SCOCtorDelegate;

    DynamicMethod method = new DynamicMethod("CreateInstance", typeof (SCO),
                             new Type[] {typeof (SPListItem), typeof (List<Vote>)});

    ILGenerator gen = method.GetILGenerator(); //Error here
    //"Cannot access non-static field 'method' in static context"

    private static SCO CreateInstance(SPListItem item, List<Vote> votes)
    {
        return SCOCtorDelegate(item, votes);
    }
}

Blog for reference: http://ayende.com/blog/3167/creating-objects-perf-implications

4
  • The child classes are known at compile time? Aug 27, 2012 at 18:25
  • Yes. ChildClass was used as an illustration, but I have a class Post : SCO for example, which can be called with: List<Post> sortedPosts = Post.SortedCollection<Post>(listItems, sortType, votes);
    – Wesley
    Aug 27, 2012 at 18:30
  • It seems like every 10th question is about building an SO clone for fun.
    – usr
    Aug 27, 2012 at 19:44
  • 1
    The problem with your IL code really that you can't access other instance fields from instance field initializer. You should use constructor (possibly static constructor) for such initialization.
    – svick
    Aug 28, 2012 at 8:32

3 Answers 3

2

I have a drop-in replacement for Activator that uses IL generation hosted here on CodePlex. You can also get it via Nuget here (a single source file include, no assemblies).

The source code for FasterActivator is here.

Usage is something like what's outlined below.

private static readonly Dictionary<Type, DynamicCreationDelegate> _cachedCreationDelegates = new Dictionary<Type, DynamicCreationDelegate>();

private static DynamicCreationDelegate CreateOrGet(Type typeToCreate)
{
    DynamicCreationDelegate result = null;

    if (!_cachedCreationDelegates.TryGetValue(typeToCreate, out result))
    {
        result = FastActivator.GenerateDelegate(typeToCreate, 
        /* List of types that make up the constructor signature of the type being constructed */
        typeof(SPListItem), typeof(List<Vote>));
        _cachedCreationDelegates.Add(result);
    }

    return result;
}

// Usage 
for (int i = 0; i < items.Count; i++) 
{ 
    var creationDelegate = CreateOrGet(typeof(genericType));
    returnlist.Add((T)creationDelegate(new object[] { items[i], votes })); 
}

Oh, and here is a generic version that ought to be faster.

private static readonly Func<SPListItem, List<T>, T> _creationFunc;
private static Func<SPListItem, List<T>, T> CreateOrGetFunc()
{
    if (!_creationFunc == null)
        _creationFunc = FastActivator.GenerateFunc<Func<SPListItem, List<T>, T>>(/* IL generator knows all type info from generic params now */);

    return _creationFunc;
}

// Usage
for (int i = 0; i < items.Count; i++) 
{ 
    var creationFunc = CreateOrGetFunc();
    returnlist.Add(creationFunc(items[i], votes )); 
}

Hope this helps!

4
  • If you don't mind, I'm having a little bit of trouble with the Func instantiating with multiple parameters in a loop. How would you write that into the top code block SortedCollection
    – Wesley
    Aug 27, 2012 at 19:03
  • Throwing an error. I might just open a new ticket and post the URL here to work it out.
    – Wesley
    Aug 27, 2012 at 19:58
  • .Post__041c49eec0a6466da11894b0455b1162(Microsoft.SharePoint.SPListItem, System.Collections.Generic.List`1<MonkeySphere.Vote>)
    – Wesley
    Aug 27, 2012 at 19:59
1

I see you've got a answer. I just uploaded to github the code of a helper class to IL constructor calls (I was supposed to have done this before, but were missing a good reason ):

The usage is something like this:

// suppose you want to call the constructor for this class  
// but generalizing the return to ISomeInterface
public class AClass : ISomeInterface
{
   public class(int intParam, String stringParam) { }
}

// construct the factory method Func<int, string, ISomeInterface>
var createAClassInstance = ReflectionHelper
   // return type + constructor params
   .CreateFactoryMethod<ISomeInterface, int, string>(typeof(AClass));

var instance = createAClassInstance(10, "hello constructor");
5
  • If this works without the library, and is reasonably fast, I would consider changing the answer.
    – Wesley
    Aug 27, 2012 at 21:15
  • System.Collections.Concurrent is missing, and I don't see it as an addable reference.
    – Wesley
    Aug 27, 2012 at 21:18
  • It is a single file, no library - perhaps someday :) Aug 27, 2012 at 21:18
  • This class is a .net4 class, change it to Dictionary<> if you're using a previous framework version... Aug 27, 2012 at 21:19
  • In fact you'll need to change another method two. What version of the framework are you using? Aug 27, 2012 at 21:22
1

If you're willing to accept some repetition, then instead of dealing with IL (which can get complicated fast, as you discovered), you can use delegates. Something like:

internal class SCO : IVotable
{
    protected static List<T> SortedCollection<T>
        (SPListItemCollection items, ListSortType sortType, List<Vote> votes,
        Func<SPListItem, List<Vote>, T> factory) where T : IVotable
    {
        var returnlist = new List<T>();
        Type genericType = typeof(T);
        for (int i = 0; i < items.Count; i++)
            returnlist.Add(factory(items[i], votes));

        // etc.
    }
}

class ChildClass : SCO
{
    public static List<ChildClass> SortedCollection
        (SPListItemCollection items, ListSortType sortType, List<Vote> votes)
    {
        return SCO.SortedCollection<ChildClass>(
            items, sortType, votes, (i, vs) => new ChildClass(i, vs));
    }
}

Doing it this way should be very fast, probably even slightly faster than when using IL emit.

1
  • Interesting. I'll take a stab at it.
    – Wesley
    Aug 28, 2012 at 20:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.