C-Sharp Help on Default Properties..Help

  • Thread starter Thread starter CodeToad
  • Start date Start date
C

CodeToad

I am using the Windows MCAD/MCSD book on VB.NET/VC.NET to refresh myself on
some C# concepts and I ran into one issue in the properties area I just do
not understand. In VB.NET this is easy to understand, in VC.NET I am lost,
can someone simplify it for me?

Here is some sample code:

public int this[int Index]
{
get
{
return intArray[Index];
}
set
{
intArray[Index] = value;
}
}

What is the dafault property? I cannot tell by reading this sample from the
book.
 
This means, you can access your object just like how you would with an
array.

For example, if your class was named FooClass, you can do something like
this:

FooClass foo = new FooClass();
int i = foo[0];

When you dereference foo with foo[0], you are actually calling the property
you just defined.

-vJ
 
you can define a property just like this:


public int MyProperty
{
get
{
return MyIntValue;
}
set
{
MyReturnValue = value;
}
}


What you see is another thing.
 
In vb.net, you create a "real" property (for example, an Item property) and
decorate it with the Default keyword, such as:

Default Public Property Item(Index As Integer) ...

You can then invoke this member by using either one of two syntax choices:

x = MyObject.Item(3)
or
x = MyObject(3)

Since Item is the Default property, you don't need to spell it out to invoke
it, and it helps you make properties that behave more or less like indexed
values.

C# doesn't have quite the same flexibility. In C# you can only create ONE
indexed property (and it is automatically named Item by default), though you
can overload it.
C# assumes you will invoke the "indexer" by using

x = MyObject[3];

Pity, because C# has no way to define multiple properties with paramters
(not just the DEFAULT indexer), and the VB.NET syntax is actually closer to
what the compiled IL looks like. To me, C# just made it confusing and
inflexible.

-Rob Teixeira [MVP]
 
Back
Top