I’m going through another developer’s code, which is shown below:
[XmlElement("AdminRecipient")] public AdminRecipient[] AdminRecipientCollection = new AdminRecipient[0];
public AdminRecipient this[ string type ]
{
get
{
AdminRecipient result = null;
foreach( AdminRecipient emailRecipient in AdminRecipientCollection )
{
if( emailRecipient.Type == type )
{
result = emailRecipient;
break;
}
}
return( result );
}
Can someone explain what’s going to happen in this line?
public AdminRecipient[] AdminRecipientCollection = new AdminRecipient[0];
The XML file that contains all of the email recipients has about 5 email addresses. But by using [0], will the foreach loop return each of those email addresses?
I have a basic understanding of indexers, but I don’t this. What does it do?:
public AdminRecipient this[ string type ]
At the end of the day, the problem here is that the application doesn’t send out an email when all 5 recipients are in the xml file. If I replace the 5 addresses with just 1 email addresses, then I’m able to get the email (which leads me to believe that there’s a logic issue somewhere here).
An indexer allows you to use a type with the same syntax as array access. One of the simplest examples would be
List<T>:That use of
x[0]is calling the indexer forList<T>. Now forList<T>the index is an integer, as it is for an array, but it doesn’t have to be. For example, withDictionary<TKey, TValue>it’s the key type:You can have a “setter” on an indexer too:
Your indexer is just returning the first
AdminRecipientin the array with a matching type – or null if no match can be found.(It’s unfortunate that the code you’ve shown is also using a public field, by the way. It would be better as a property – and probably not an array, either. But that’s a separate discussion.)
EDIT: Regarding the first line you highlighted:
That will create an array with no elements, and assign a reference to the
AdminRecipientCollectionfield. With no further changes, theforeachloop would not have anything to iterate over, and the indexer will always return null.However, presumably something else – such as XML serialization – is assigning a different value to that field – populating it with more useful data.