ASP.NET Hosting

"The C# compiler won't let me do it" - answer

Drew knows his thing. He was the one who gave the right explaination for my quiz. I just copy it here:

DictionaryEntry is a structure and you're foreaching which means the instance is coming from IDictionaryEnumerator.Current therefore assigning to only the local copy. This would be a nasty problem if people forgot about the semantics of value types vs. ref. types, so the C# compiler prevents you from doing this.

However, I agree with Eric Newton that the message from the compiler should be clearer! The current one is very confusing.

Now, if you want something even more confusing, you can try the following code:

IDictionary dictionary = new Hashtable();
dictionary["dummy"] = "dumb";
IEnumerator enumerator = dictionary.GetEnumerator();
while (enumerator.MoveNext())
{
  DictionaryEntry entry;

  entry = (DictionaryEntry) enumerator.Current;
  entry.Value = 0; // no compiler error, but "error" nonetheless
}
Console.WriteLine(dictionary["dummy"]);

This one compiles, but doesn't do what you'd expect at first. Guess what the output will be... So yes, the compiler message is useful (even if not easy to understand), but doesn't fire in all the cases...

No Comments