Showing posts with label Compiler. Show all posts
Showing posts with label Compiler. Show all posts

Tuesday, March 20, 2007

The Indexer Name

Any guesses why the following class won't compile?

public class SuperSimpleIndexerClass
{
__public double this[int index]
__{
____get { return 0; }
__}

__public double Item
__{
____get { return 0; }
__}
}


It has to do with the way indexers are internally represented in C#. By default, indexers have the name "Item." Thus, the indexer property and the explicit Item property will have a naming collision. We can fix this problem by providing the following attribute.

public class SuperSimpleIndexerClass
{
__[System.Runtime.CompilerServices.IndexerName("TheItem")]
__public double this[int index]
__{
____get { return 0; }
__}

__public double Item
__{
____get { return 0; }
__}
}


Now, this indexer will have the name TheItem.

Monday, July 18, 2005

Please, Let Me Keep My Unassigned Variables

If you compile code in C# that contains uninitialized variables, you will receive a compilation error in VS. C# imposes definite assignment, which requires that all variables be assigned before they are used (from Programming C#). I typically resolve this by assigning my object vars to null or, in the case of primitives, something like int.MaxValue or -1.