Using ExpandoObject to create objects that you can add properties, methods, and events to.
Buy “C# 6.0 Cookbook” in early release.
Editor’s note: This is an excerpt from “C# 6.0 Cookbook,” by Jay Hilyard and Stephen Teilhet. It offers more than 150 code recipes to common and not-so-common problems that C# programmers face every day. In it, you’ll find recipes on asynchronous methods, dynamic objects, enhanced error handling, the Rosyln compiler, and more.
You want to be able to build up an object to work with on the fly at runtime.
ExpandoObject to create an object that you can add properties, methods, and events to and be able to data bind to in a user interface.
We can use
ExpandoObject to create an initial object to hold the
Name and current
Country of a person.
dynamic expando = new ExpandoObject(); expando.Name = "Brian"; expando.Country = "USA";
Once we have added properties directly, we can also add properties to our object in a more dynamic fashion using the
AddProperty method we have provided for you. One example of why you might do this is to add properties to your object from another source of data. We will add the
Think labels, not boxes
Python tuples have a surprising trait: they are immutable, but their values may change. This may happen when a tuple holds a reference to any mutable object, such as a list. If you need to explain this to a colleague who is new to Python, a good first step is to debunk the common notion that variables are like boxes where you store data.
In 1997 I took a summer course about Java at MIT. The professor, Lynn Andrea Stein — an award-winning computer science educator — made the point that the usual “variables as boxes” metaphor actually hinders the understanding of reference variables in OO languages. Python variables are like reference variables in Java, so it’s better to think of them as labels attached to objects.
Here is an example inspired by Lewis Carroll’s Through the Looking-Glass, and What Alice Found There.
Tweedledum and Tweedledee are twins. From the book: “Alice knew which was which in a moment, because one of them had ‘DUM’ embroidered on his collar, and the other ‘DEE’.”
A new mantra for your next (programming) meditation session.