F
F
fiskoner2020-03-02 17:09:11
.NET
fiskoner, 2020-03-02 17:09:11

An embedded statement cannot be a declaration or a statement with an identifier?

private void getWmiDecodeFromNhtsaApi()
        {
            string url = "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeWMI/" + wmi + "?format=json";
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            try
            {
                var tmp = client.GetAsync(url).Result;
                if (tmp.IsSuccessStatusCode)
                    var result = tmp.Content.ReadAsStringAsync();
            }
            catch (Exception err)
            {
                // error handling
            }
        }
There is a request for api, code:

visual studio swears at the line
var result = tmp.Content.ReadAsStringAsync();

"embedded operator cannot be a declaration or an operator with an identifier"

The api code is taken from the official documentation - https://vpic.nhtsa.dot.gov/api/Home/Index /Language...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Peter, 2020-03-02
@petermzg

The official documentation also contains a lot of bad code, even from microsoft.
Define your method in async and get rid of bad code with ".Result;"

B
breathtaking, 2020-03-04
@breathtaking

Without delving into the essence of your code, specifically this error is as follows:
You have an operator embedded in an if that is a variable declaration (and its initialization). Swears, because the operation is meaningless. After exiting the if block, the result will be lost. Therefore, we first declare the variable, and then we initialize it inside the if:

Task<string> result;

if (tmp.IsSuccessStatusCode)
    result = tmp.Content.ReadAsStringAsync();

Or use the result inside an if block:
if (tmp.IsSuccessStatusCode) {
    var result = tmp.Content.ReadAsStringAsync();
    Console.WriteLine(result.Result);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question