Basic OO with cats and dogs. |
I create the traditionel object structure to support me explain what I mean. Animal is a pure abstract concept, Cat is an Animal and so is Dog.
Make the animals make som noise |
What I want is to have a list of animals containing cats and dogs and then call the MakeSound for each animal in the list.
As in C# < 4.0 |
Result of program with static method binding |
Use of var keyword |
With C# 3.5 the var keyword was introduced. One might think that this changed the way this would work as the programmer no longer defines the type and the framework should therefore be able to select a better method implementation automatically. The answer is that the var is just a way to have the compiler derive the type instead of the programmer. This is all done at compile time and the best match will therefore still be the method that operates on the interface.
Handle the objects as dynamic instead |
The dynamic keyword was introduced with C# 4.0 and this changes the possibilities when writing code like this. When treating every object in the list as a dynamic object, the compiler won't bind to any method but will leave it to the runtime to make the connection. This means that the type of every object is considered and handled on its own and the items in the list won't nescesarily result in the same method being called. This can be very usefull when iterating tree structures etc. The downside is that you will have no intellisense and no compile time validation when writing the code.
Output when treating the objects as dynamic |
Related posts:
Wrapping objects with interfaces
Dynamic duck typing in .Net 3.5
No comments:
Post a Comment