0

I was about to use the below C# code.

await using (var producerClient = new EventHubProducerClient(ConnectionString, EventHubName))
{
    using EventDataBatch eventBatch = await producerClient.CreateBatchAsync();
    eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes(eventData)));
    await producerClient.SendAsync(eventBatch);
}

But in build server this is getting failed as the above is C# 8.0 code and build server supports till C# 7.0 code only. Can someone please help me convert the above code from C# 8.0 to C# 7.0 as I couldn't make it work?

dymanoid
  • 14,771
  • 4
  • 36
  • 64
Ramesh
  • 392
  • 1
  • 12
  • 39
  • 6
    Use curly brackets for the scope of the second `using` (like the first `using` is already doing). – Matthew Watson Mar 16 '20 at 12:03
  • 2
    Another problem might be `await using`. [Related](https://stackoverflow.com/q/58610350/1997232) – Sinatr Mar 16 '20 at 12:08
  • 4
    Why not just fix the build server instead? – DavidG Mar 16 '20 at 12:09
  • 2
    If you can compile the code locally, you can try using ILSpy to decompile it to equivalent code in an older language version. – Daniel Mar 16 '20 at 12:12
  • @PavelAnikhouski If the build server doesn't know about C#8, this won't help. – DavidG Mar 16 '20 at 12:30
  • @DavidG for the time being, we can't change the build server settings. That's why I would like to convert to C# 7.0. I thought it would be simple conversion. I think it has "await using" as extra and second using. We just need to figure out equivalent for C# 7.0. I guess if someone knows both the versions, he would be able to help. – Ramesh Mar 16 '20 at 12:39
  • 1
    I'd be more concerned right now that you have this code and don't understand what it is doing. So go ahead and use Stephen's answer below, but please figure out what this code is doing before you proceed. – DavidG Mar 16 '20 at 12:44

1 Answers1

11

In the long run, you're certainly better off updating your build server. You'll need to do that sooner or later anyway.

C# 8.0 has using declarations, which transform this:

using var x = ...;
...

into this:

using (var x = ...)
{
  ...
}

The other C# 8.0 feature in this code is await using, which transforms code like this:

await using (var x = ...)
{
  ...
}

into something similar to this:

var x = ...;
try
{
  ...
}
finally
{
  await x.DisposeAsync();
}

Applying both of these transformations by hand gives you:

var producerClient = new EventHubProducerClient(ConnectionString, EventHubName);
try
{
  using (EventDataBatch eventBatch = await producerClient.CreateBatchAsync())
  {
    eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes(eventData)));
    await producerClient.SendAsync(eventBatch);
  }
}
finally
{
  await producerClient.DisposeAsync();
}
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810