Home > Net >  Why am I getting an error with this using statement without brackets? .Net 6
Why am I getting an error with this using statement without brackets? .Net 6

Time:01-07

var webRequest2 = new HttpRequestMessage(HttpMethod.Get, "/my/url");
var response2 = client2.Send(webRequest2);
var reader2 = new StreamReader(response2.Content.ReadAsStream());
var responseBody2 = reader2.ReadToEnd();

using var jsonDoc = JsonDocument.Parse(responseBody2);

Getting

error CS1002: ; expected
error CS0103: The name 'jsonDoc' does not exist in the current context

on that last line

CodePudding user response:

This issue explains what's going on:

Unfortunately this is a limitation of Roslyn. You cannot use using statements as global script variables.

You can only use using statements inside a scope. Even if you put curly braces around just that line:

{
    using var jsonDoc = JsonDocument.Parse(responseBody2);
}

Old answer:

The using statement was introduced in C# 8.0. Your project is probably using a lower version, so it only understands using as a using directive.

  •  Tags:  
  • Related