1

I want to allow the user, when searching for a Platypus, to enter either the Platypus' ID or Name (or portion of a name).

The database is down right now, so I can't test this code, but the fact that I'm assigning to kvp twice doesn't seem right. Anyway, first my code:

String SearchVal = textBoxPlatypusNumOrPartialName.Text.Trim();
int PlatypusID;
int.TryParse(SearchVal, out PlatypusID);

Dictionary<int, string> CandidatePlatypusDict = PlatypusID > 0 ? PlatypusSetupData.GetPlatypusById(PlatypusID) :        PlatypusSetupData.GetCandidatePlatypusFromName(SearchVal);

KeyValuePair<int, String> kvp = new KeyValuePair<int, string>();
using (var getPlatypusIDAndNameDlg = new GetPlatypusForm(CandidatePlatypusDict)) {
    DialogResult dr = getPlatypusIDAndNameDlg.ShowDialog();
    if (dr == DialogResult.OK) {
        kvp = getPlatypusIDAndNameDlg.PlatypusKVP; 
    }
}

...Now, if I try this instead:

KeyValuePair<int, String> kvp; // = new KeyValuePair<int, string>();

I get: "Use of unassigned local variable 'kvp'"

And I can't assign null as KeyValuePair, as it is a non-nullable type.

Is this instantiation of kvp followed by assignment to it okay, and if not, how can I work around it?

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • possible duplicate of [The default for KeyValuePair](http://stackoverflow.com/questions/1641392/the-default-for-keyvaluepair) – Sam Harwell Jul 09 '12 at 17:15
  • Out of interest, why use keyvaluepair for search results? Could you not have a List instead for example? It simplifies many of these kind of problems as you only deal with Platypus' then - which is what you are searching for. I've really enjoyed these questions of yours! – dash Jul 09 '12 at 17:21
  • @-: Thanks, but why (have you enjoyed them)? – B. Clay Shannon-B. Crow Raven Jul 09 '12 at 17:32

2 Answers2

3

Is this instantiation of kvp followed by assignment to it okay, and if not, how can I work around it?

Well it's okay - but you might instead want:

KeyValuePair<int, String> kvp;
using (...) {
   kvp = dr == DialogResult.OK ? getPlatypusIDAndNameDlg.PlatypusKVP 
                               : /* some other value here */;
}

That way it's clearly only assigned once, but is always assigned. Next you need to work out what value you want it to have in the situation where dr isn't DialogResult.OK.

Sam Harwell
  • 97,721
  • 20
  • 209
  • 280
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

If it makes sense for your KeyValuePair to be null, then declare it as nullable:

KeyValuePair<int, String>? kvp = null;

But be sure you use the nullability (it's totally a word) correctly later in your code.

Edit:

Make use of the properties that it will now have like

kvp.HasValue;
kvp.Value;

and the method

kvp.GetValueOrDefault();

Stefan H
  • 6,635
  • 4
  • 24
  • 35