Thursday, 26 April 2012

C# default properties

Thursday, 26 April 2012 01:53

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:



  1. Why cant you just override ToString()?

    1. Hey, Uri. Thanks for your comment. In this contrived example, certainly overriding ToString() would be easier. However, the goal of the article was to showcase C# type conversion operators. The consequence is that with the conversion operator, you can apply comparison operations between string and Person types. So, in the above scenario, new Person { Name = "John Public", Age = 25 } == "John Public" would evaluate to True, whereas you would get a syntax error had you simply overridden ToString().

  2. you could buy more properties but each of those properties will go up in price and if you've leveraged your investments with mortgages your return on investment will be even greater.deyaar properties


Toggle Footer