Jay F1 Jay F1 -4 years ago 77
C# Question

Bool does not exist in current context but declared in same way as other variables

I have a bool that the compiler says does not exist in the current scope, however all the other variable are declared and used in the same place/way. Code below, some class names changed and code simplified but the structure remains the same.

iDReq does not exist in the current context


if (button.Click) {
string sourceFileName = "";
string destPathFileName = "";
int exportCount = 0;
bool iDReq = true;
iDReq = (System.Windows.Forms.MessageBox.Show("Include ID in file names?", "ID",MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes);
foreach (KeyValueCollection item in SearchControl.SelectedItems)
{
Class.Document doc = Class.Document.GetDocument((long)item["id"].Value);
{
sourceFileName = @"\\server\share" + @"\" + Convert.ToString(doc.GetExtraInfo("docFileName"));
string fileExtension = System.IO.Path.GetExtension(sourceFileName);
//Line below is the one that the compiler does not like.
iDReq = true ? destPathFileName = destPath + @"" + doc.Description + " " + "(" + doc.ID + ")" + fileExtension : destPathFileName = destPath + @"" + doc.Description + fileExtension;
try {
System.IO.Directory.CreateDirectory(destPath);
System.IO.File.Copy(sourceFileName,destPathFileName,true);
System.Windows.Forms.Clipboard.SetText(destPathFileName);
exportCount ++;
}
catch(Exception ex)
{
ErrorBox.Show(ex);
}
}
}
}


Is it because it's a boolean value or am I missing something else?

Answer Source

I think your ternary is badly written, but I am not sure about what you want. I would rewrite you this as a plain if/else. I love ternary operator, but it is just sugar.

I think you are looking for this:

destPathFileName = iDReq == true
    ? (destPath + @"" + doc.Description + " " + "(" + doc.ID + ")" + fileExtension)
    : (destPath + @"" + doc.Description + fileExtension);

and iDReq == true is superflous.

also you can write:

destPathFileName = destPath + @"" + doc.Description
    + (iDReq ? " (" + doc.ID + ")" : string.Empty)
    + fileExtension;

by the way, @"" is string.Empty.

and with string interpolation:

destPathFileName = destPath + doc.Description
    + (iDReq ? $" ({doc.ID})" : string.Empty)
    + fileExtension;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download