Thursday, 26 April 2012
2 comments

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):

person.cs

 

 

 

I “new” it up in a collection like this:

main.cs-1

Now, let’s say that I set up a foreach loop which does something to the collection, like this:

main.cs-2

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:

 consoleapp1-output

The trick is to use C# conversion operators, like so:

person.cs-2

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:

consoleapp1-output-2

2 comments :

  1. Why cant you just override ToString()?

    ReplyDelete
    Replies
    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().

      Delete

 
Toggle Footer
Top