I need to create a delegate to a non-static method of a class. The complications is that at the time of creation I don\'t have an intance to the class, only its class defini
What's wrong with just passing an instance in like this?
// Creation.
Action bar = foo =>
{
foo.Baz();
};
// Invocation.
bar(new Foo());
It does all you need it to: it encapsulates the logic you want to pass around, and can be invoked on an arbitrary class instance.
Edit: If you're restricted to using a delegate of a certain signature (not allowing an instance to be passed explicitly as a parameter), then you could use some form of "instance provider" which is specified at the time of the delegate's creation, but can be mutated later to provide the appropriate instance when it becomes available, e.g.:
class Provider
{
public T Instance { get; set; }
}
static Action Create(Provider provider)
{
return () =>
{
provider.Instance.Baz();
};
}
// ...
// Creation.
var provider = new Provider();
var bar = Create(provider);
// Invocation.
provider.Instance = new Foo();
bar();
Of course, this is a bit convoluted, and requires an additional object to be passed around, so perhaps it's not ideal!