Dynamic Binding in C#: Buu Nguyen
Dynamic Binding in C#: Buu Nguyen
DYNAMIC BINDING IN C#
Buu Nguyen
Vice President of Technology, KMS Technology
Agenda
What is dynamic binding
How is it implemented
When do we need it
C# Language Evolution
C# 4.0
C# 3.0
C# 2.0
LINQ (*) Auto- properties Collection initializer Object initializer Anonymous types Extension methods Partial methods Lambda expressions Expression trees
C# 1.0
Generics (*) Nullable types Anonymous methods Yield return Partial type Static class Namespace alias
Dynamic binding (*) Named arguments Optional parameters Generic variance Field-like events Robust locking Better COM interop
Dynamic Biding
All bindings happen during
run time
Static Binding
Dynamic Binding
How Is It Implemented?
CIL, the compiler packages the call and sends it to the Dynamic Language Runtime At run time, the DLR performs binding and execution
becomes
Process in a nutshell
C# dynamic
compiled
Dynamic Objects
builds
User-defined or from other languages
Call Sites
cached
uses
IDynamicMetaObjectProvider
Delegate
Expression Tree
emits
DLR
C# Binder builds
Key Scenarios
1. Access a member with only knowledge of its
Key Scenarios
1. Access a member with only knowledge of its
Access Members
Reflection
Dynamic Type
Multiple Dispatch
Method is selected based
on both the runtime type of the target object and those of the methods arguments
Dispatch Example
Key Scenarios
1. Access a member with only knowledge of its
Key Scenarios
1. Access a member with only knowledge of its
ExpandoObject
DynamicObjects Operations
Name TryGetMember TrySetMember TryDeleteMember TryInvokeMember TryConvert TryCreateInstance TryInvoke TryBinaryOperation TryUnaryOperation TryGetIndex TrySetIndex TryDeleteIndex Description Member getter, e.g. obj.Name Member setter, e.g. obj.age = 10 Member removal (no equivalent in C#) Method invocation, e.g. obj.Invoke() Casting, e.g. (int)obj Object creation (no equivalent in C#) Self invocation, e.g. obj(10) Binary operation, e.g. obj + 10 Unary operation, e.g. !obj Indexer getter, e.g. obj[key] Indexer setter, e.g. obj[key] = value Indexer removal (no equivalent in C#)
StaticInvoker
StaticInvoker
Restrictions
Restriction #1
Doesnt work with extension methods
Restriction #2
Cant resolve static members or constructors
on a dynamic type
Restriction #3
Method groups, anonymous methods and
Restriction #4
Thank You!
[email protected] http://vn.linkedin.com/in/buunguyen
http://www.twitter.com/buunguyen
http://www.facebook.com/buunguyen
References
DLR specs from
http://dlr.codeplex.com/documentation C# in Depth, 2nd, Jon Skeet, Manning, 2010 Pro DLR in .NET 4.0, Chaur Wu, Apress, 2010