After reading this post and links I still have 2 questions
Question #1
What is the criteria so that I would be able to execute dynamic code in c# ? must the target classes/objects rely on .net clr
? I mean if someone gives me a Pascal DLL , I guess I won't be able to use its code via dynamic ( or will ? )..so: What are the requirements for dynamic to work ?
Question #2
For example : In script object - in order to increase an int the code should be :
Scriptobj.SetProperty("Count", ((int)GetProperty("Count")) + 1);
With dynamic I can do :
scriptobj.Count += 1;
Does it mean that the scriptobj's class programmers wrote a supportive code which enables DLR to do =+1
?
ScriptobjClass : DynamicObject
{
...
public override bool TryInvokeMember (...when +=1 so do a+1....)...
}
Im missing something essential here.
Is it like : "we're building a class but we should also let .net DLR access it - so let's write more code so that this class also support operations which will allow .net users to access this class via dlr" ?
Lets start by explaining what the DLR allows you to do, first:
There are two facets to the DLR the first is that it allows dynamic binding of objects at run time. For example:
The dynamic d can be assigned objects of any type and call their methods and properties. A more striking example:
This works with any class that has a method "SomeMethod" returning an int. The strong typed way to do this would be create an interface with "SomeMethod":
Note that this is not something which could not be done before with reflection, but the DLR and the dynamic keyword makes this much simpler. The DLR also creates and caches expression trees for the calls so using the DLR is almost always more efficient than reflection.
The real strength of the DLR however is not just run time binding, it actually allows you to create objects that behave dynamically. Basically it lets you to specify what happens when you call a method or property that does not exist in the actual runtime object bound to the dynamic variable. This allows the CLR to be used for dynamic languages and to provide easy interoper with dynamic langues , create easy to use parsers which can represent a DOM as a dynamic object or ORM's that can represent ad-hoc queries as objects, etc..
More detailed information about the DLR can be found in its codeplex project documentation page. Especially worthwhile are the overview and the Sites, Binders, and Dynamic Object Interop Spec documents.
Now to your questions:
Question 1: No you can't interact by magic with any dynamic language, there must be some supported interop (which may be facilitated by the DLR) to do so (I don't know what you meant by Pascal dll.)
Question 2: ScriptObjectClass uses the DLR facilities (by extending DynamicObject) to get and set the Count property dynamically as if it was an actual property of ScriptObjectClass (if you're curious see Sites, Binders, and Dynamic Object Interop Spec for exactly how this is done.)