C#: Give your object a Default Property (pietschsoft.com)

submitted by crpietschmanncrpietschmann(11.3k) 5 years, 2 months ago

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?

9 comments |category: |Views: 263

tags: another

new Add a live kick counter to your blog >> liveImage

You can even customize the image by choosing your own colors, and then clicking the button below to update the preview and the html code:

  • "Kick It" text
  • "Kick It" background
  • kick count text
  • kick count background
  • border

Simply copy and paste this HTML into your blog post.


Users who kicked this story:
Comments:

posted by marcoowmarcoow(185) 5 years, 2 months ago 0

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

Reply

posted by gavinjoycegavinjoyce(25.7k) 5 years, 2 months ago 0

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";

Reply

posted by luciolucioluciolucio(0) 5 years, 2 months ago 0

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

Reply

posted by yesthatmcgurkyesthatmcgurk(4063) 5 years, 2 months ago 0

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

Reply

posted by luciolucioluciolucio(0) 5 years, 2 months ago 0

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

Reply

posted by luciolucioluciolucio(0) 5 years, 2 months ago 0

Thought so...

Reply

posted by MarkoBarkoMarkoBarko(0) 5 years, 2 months ago 0

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

Reply

posted by crpietschmanncrpietschmann(11.3k) 5 years, 2 months ago 0

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.

http://msdn2.microsoft.com/en-us/library/2b6akew6(VS.71).aspx

Reply

posted by luciolucioluciolucio(0) 5 years, 2 months ago 0

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

Reply

information Login or create an account to comment on this story