Reputation: 353
I'm porting an application from VB.NET to C# and found out that I cannot use .ItemOf
in C#, but if I do it without .ItemOf
it seems to work. However, are the following two snippets actually doing the same thing?
VB
Public Shared Settings As NameValueCollection
'some code
Dim key As XmlNode
For Each key In node.ChildNodes
MobileConfiguration.Settings.Add(key.Attributes.ItemOf("key").Value, key.Attributes.ItemOf("value").Value)
Next
'some code
C#
public static NameValueCollection Settings;
//some code
foreach (XmlNode key in node.ChildNodes)
MobileConfiguration.Settings.Add(key.Attributes["key"].Value, key.Attributes["value"].Value);
//some code
Upvotes: 0
Views: 73
Reputation: 239646
Yes, C# indexer syntax is the equivalent of the VB code's .ItemOf()
calls. You can see this if you look at the documentation for ItemOf
. If your language preferences at the top are set to C#
1, the example looks like this:
using System; using System.IO; using System.Xml; public class Sample { public static void Main(){ XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" + "<title>Pride And Prejudice</title>" + "</book>"); //Create an attribute collection. XmlAttributeCollection attrColl = doc.DocumentElement.Attributes; Console.WriteLine("Display all the attributes in the collection...\r\n"); for (int i=0; i < attrColl.Count; i++) { Console.Write("{0} = ", attrColl[i].Name); Console.Write("{0}", attrColl[i].Value); Console.WriteLine(); } } }
If your language settings are set to VB, you'll see this as the example:
Imports System Imports System.IO Imports System.Xml public class Sample public shared sub Main() Dim doc as XmlDocument = new XmlDocument() doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" & _ "<title>Pride And Prejudice</title>" & _ "</book>") 'Create an attribute collection. Dim attrColl as XmlAttributeCollection = doc.DocumentElement.Attributes Console.WriteLine("Display all the attributes in the collection...") Dim i as integer for i=0 to attrColl.Count-1 Console.Write("{0} = ", attrColl.ItemOf(i).Name) Console.Write("{0}", attrColl.ItemOf(i).Value) Console.WriteLine() next end sub end class
C# reserves special syntax for indexers, and ItemOf
is the indexer for the XmlAttributeCollection
class.
1I know a lot of people haven't found this yet in the revamped documentation:
Upvotes: 6
Reputation: 21
It looks like .ItemOf("key") just finds the value that corresponds with that key. In C# this is just done by placing ["key"] at the end of the object. So yes, they are doing the same thing
Upvotes: 2