AndrewG
AndrewG

Reputation: 1429

C# Dynamic indexer

Does anybody know if it's possible to call method on CLR object via indexer using dynamic lang features? For instance, myClrObj["SuperMethod"] () which I can easily do in javascript.

thank in advance.

Upvotes: 6

Views: 4323

Answers (2)

jbtule
jbtule

Reputation: 31799

You could use the opensource Dynamitey available via nuget, it wraps the DLR API to make it simpler to dynamically call a method by name, works for both dynamic and poco objects. Faster than reflection for poco objects.

Dynamic.InvokeMember(myClrObj,"SuperMethod")

Upvotes: 0

flq
flq

Reputation: 22849

There may be better ways, but one way I'd know how to do it is:

  • Create a class that inherits from DynamicObject
  • override the suitable method to capture the access via indexer
  • Construct and cache a delegate that corresponds to the method that you find via the provided indexer argument
  • Provide an extension method that suitably makes your object appear dynamic, with the correct DynamicObject specialization instantiated.

    dynamic obj = myObj.AsIndexedObj(); obj["Do"]();

Upvotes: 1

Related Questions