Search code examples
c#csx

CSX getting current submission instance


I'm trying to get current submission instance in csharp csx script. I need to invoke script method with reflection:

using System.Reflection;

void Foo()
{

}

var foo = MethodBase.GetCurrentMethod().DeclaringType.GetMethod("Foo");
foo.Invoke(???, null);

I cannot use this keyword, as it's not available in scripting context:

error CS0027: Keyword `this` is not available in the current context

Trying to invoke foo.Invoke(null, null) fails because Foo is not a static method.

Does anyone know if this is possible?


Solution

  • While it's not the most elegant solution, it's possible to get instance using expression trees.

    Anywhere in your script place following code:

    using System.Reflection;
    using System.Linq.Expressions;
    
    void Stub() { }
    
    object GetInstance(Expression<Action> expr)
    {
        var invoke = (MethodCallExpression)expr.Body;
        return ((ConstantExpression)invoke.Object).Value;
    }
    
    var This = GetInstance(() => Stub());
    

    Now the This variable contains current instance of Submission, and one can safely call foo.Invoke(This, null)