I’d like to start out the Coders’ Corner section of this blog with a simple C# trick that I call “default properties”, having come from the VB world.
Suppose that I have this class called Person (code screen shots taken from Visual Studio 11 Beta):
I “new” it up in a collection like this:
Now, let’s say that I set up a foreach loop which does something to the collection, like this:
What I would like it to do is to use p’s Name property, without having to tell it explicitly within the context of WriteLine().
As is, the above code would give me this output:
The trick is to use C# conversion operators, like so:
When WriteLine() is used, the system knows that the method expects a string, and finds the implicit cast operator which converts a Person into a string.
And the output: