-5

I want to check if my variable(crphoto1) is null. If crphoto1 is null, crPhoto1Data should be null and when crphoto1 is not null crPhoto1Data should be like this byte[] crPhoto1Data = File.ReadAllBytes(crphoto1);. The code belows gives me error how can I fix it?

if (string.IsNullOrEmpty(crphoto1))
{
    string crPhoto1Data = "";
}
else
{
    byte[] crPhoto1Data = File.ReadAllBytes(crphoto1);
}


var ph1link = "http://" + ipaddress + Constants.requestUrl + "Host=" + host + "&Database=" + database + "&Contact=" + contact + "&Request=tWyd43";
string ph1contentType = "application/json";
JObject ph1json = new JObject
{
    { "ContactID", crcontactID },
    { "Photo1", crPhoto1Data }
};
  • What is the error you're getting? – Rufus L Feb 12 '19 at 04:03
  • @RufusL in { "Photo1", crPhoto1Data } the error is "The name 'crPhoto1Data' does not exist in the current context" –  Feb 12 '19 at 04:07
  • 1
    You should update your question with the error message rather than in the comments. The error means that you have to declare the variable outside of the `if` block because variables are scoped to the block in which they're declared. And you can't set it to more than one type. – Rufus L Feb 12 '19 at 04:09
  • how can I fix this? –  Feb 12 '19 at 04:10
  • The scope of both versions of `crPhoto1Data` (same name with different types) is wrong. – John3136 Feb 12 '19 at 04:17
  • Possible duplicate of [C# local variable scope](https://stackoverflow.com/questions/12060748/c-sharp-local-variable-scope) – ProgrammingLlama Feb 12 '19 at 04:23
  • @John3136 how can I fix this? –  Feb 12 '19 at 04:24

1 Answers1

0

The problem is that you're trying to use a variable that is declared inside a block with a narrower scope (you define crPhoto1Data inside the if block). Another problem is that you're trying to set it to more than one type.

One way solve this is to create the JObject in an if/else statement (or using the ternary operator as in my sample below):

JObject ph1json = string.IsNullOrEmpty(crphoto1)
    ? new JObject
    {
        {"ContactID", crcontactID},
        {"Photo1", ""}
    }
    : new JObject
    {
        {"ContactID", crcontactID},
        {"Photo1", File.ReadAllBytes(crphoto1)}
    };
Rufus L
  • 36,127
  • 5
  • 30
  • 43
  • Wouldn't it be shorter and easier to just have one `new JObject` and set `{"Photo1", string.IsNullOrEmpty(crphoto1) ? "" : File.ReadAllBytes(crphoto1)}`? – Tom Feb 12 '19 at 08:51
  • I assume it's just for clarity, Since OP doesn't really seem to take real note as shown in the comments of his first post. – user8478480 Feb 12 '19 at 09:07