Search code examples
c#asynchronousasync-awaitusingc#-7.0

Converting C# 8.0 to C# 7.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?


Solution

  • 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();
    }