Monday November 30th

Friday November 27th

C#: Give your object a Default Property

I've seen/used objects within the .NET Framework that have default properties (ie: SqlDataReader, System.Collections.Generic.List). Now how exactly do I give my own custom object type a default property?


I don't get it- why's that peoperty a "default" property and not just a simple property? What's so special about it?

The default property contains the 'this' keyword:

public Person this[int index]
get { return _people[index]; }
set { _people[index] = value; }

This allows you to access a person as follows:

club[0].Name = "John";

instead of

club.People[0].Name = "Joe";

But that's an indexer... where did the name "Default property" come from?

BAAARRRR! You fail, default != indexer. Sorry, try again.

Hey mr. Troll, very nice and intelligent comment, thank you so much. How about explaining the difference now?

Thought so...

well, maybe the author is coming from VB.NET because the indexer is specified by using the "Default" keyword. maybe?

Sorry for the confusion. The reason I called it a Default Property is because Microsoft has called it that in MSDN. Therefore, I have changed the title of my post to more accurately reflect what I've written about. Sorry for any confusion that may have been caused.

That article says "The C# equivalent of a default Item property is an indexer." So it's the same after all. Thanks crpietschmann.

Commenting on Stories is limited for now and will open up to those recommended by the community. Learn how
Loading DotNetKicks...
brought to you by the Kicks Network