Would prepending an empty string to HashTable.Add() possibly be the culprit of "value does not fall within the expected range"?

StackOverflow https://stackoverflow.com/questions/15776442

Pergunta

I can't for the life of me figure out why the legacy code is doing this:

HashSiteMapping.Add(""+sm.SiteNumber, sm.LocationNumber);

...when this seems more sensible:

HashSiteMapping.Add(sm.SiteNumber, sm.LocationNumber);

I would just shrug my shoulders and chock it up to the general bizarreness of this code, but I'm getting "value does not fall within the expected range" in this code and am wondering if that might be the problem. In fuller context, the code was this:

IEnumerator en = mFile.Map.Mappings.GetEnumerator();

while (en.MoveNext())
{
    SiteMapping sm = (SiteMapping) en.Current;      
    HashSiteMapping.Add(""+sm.SiteNumber, sm.LocationNumber);
}

...and I changed it to this:

IEnumerator en = mFile.Map.Mappings.GetEnumerator();

while (en.MoveNext())
{
    SiteMapping sm = (SiteMapping) en.Current;      
    if (!HashSiteMapping.Contains(sm.SiteNumber))
    {
        HashSiteMapping.Add(sm.SiteNumber, sm.LocationNumber);
    }
}

...but I still get, "value does not fall within the expected range"

Foi útil?

Solução

I am not familiar with HashSiteMapping. Is this a custom class? Can you provide a link or defining code?.

My best guess is there are instances where your SiteMapping SiteNumber is null or empty. In that case, your original code would be doing something like this:

IEnumerator en = mFile.Map.Mappings.GetEnumerator();

while (en.MoveNext())
{
    SiteMapping sm = (SiteMapping) en.Current;
    if (String.IsNullOrEmpty(sm.SiteNumber))
    {
      HashSiteMapping.Add(String.Empty, sm.LocationNumber);
    }
    else
    {
      HashSiteMapping.Add(sm.SiteNumber, sm.LocationNumber);
    }
}

Notice that even though the code above has no comments, what is going on is still easier to understand than the mystery code you were left to work with.

The 2nd version you tried (shown below) could be failing because the SiteNumber and LocationNumber together both create a type of composite key (again I'm guessing because I don't know the HashSiteMapping definition)

while (en.MoveNext())
{
  SiteMapping sm = (SiteMapping) en.Current;        
  if (!HashSiteMapping.Contains(sm.SiteNumber))
  {
    HashSiteMapping.Add(sm.SiteNumber, sm.LocationNumber); // What if LocationNumber has not been included yet?
  }
}

Consider:

|_SiteNumber__|_LocationNumber_|
| "Warehouse" |      "A1"      |
| "Warehouse" |      "B1"      |
|     NULL    | "Boss'sOffice" |
|     NULL    |"JanitorCloset" |
|     NULL    |   "RestRoom"   |

You certainly would not want to get those all confused!

Hope that helps.

Outras dicas

You may want to hook in an assert in debug build and watch for values that violate something defined as "expected range" for the HashSiteMapping class--

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top