C# 6

In order to experiment with the features from C# 6, which are new to me, I have set-up a VisualSudio 2017 Solution and added it to my GitHub repository.

The solution contains two projects:

  • a Class Library (.NET Framework) named CS6
  • a Unit Test Project (.NET Framework) named CS6.Test

The project CS6 offers a dummy implementation of a Worker class responsible with executing an action and to asynchronously log if the action executed with success or if an error occurred. In order to log information Worker class makes use of Logger class.

Below is the list of all new features used in the solution code:

  • Read-only Auto-properties<
  • Auto-Property Initializers
  • nameof Expressions
  • Expression-bodied function members
  • String Interpolation
  • Null – conditional operators
  • Exception filters
  • await in catch and finally blocks
  • index initializers
  • using static

Read-only Auto-properties, Auto-Property Initializer

public class Worker: IDisposable
{
    public Worker(Logger logger, string name = null)
    {
        if (name != null)
        {
            Name = name;
        }

        Logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }
    
    public string Name { get; } = "Default-Name";
    
    private Logger Logger { get; }
    
    ...    
}

nameof Expressions

public class Worker: IDisposable
{
    public Worker(Logger logger, string name = null)
    {
        ...
        Logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }
    ...
}

Expression-bodied function members, String Interpolation

public class Worker: IDisposable
{
    ...
    public override string ToString() => $"Worker: {Name}";
}
public class Logger : IEnumerable, IDisposable
{
    ...
    private static bool IsLine(string text) => text != null && !text.Contains(Environment.NewLine);
}

Null – conditional operators

public class Worker: IDisposable
{
    ...
    public void Dispose()
    {
        Logger?.Dispose();
    }
}

Exception filters, await in catch and finally blocks

public class Worker: IDisposable
{
    ...
    public async Task Execute(Action operation)
    {
        try
        {
            operation();
            await Logger.WriteLineAsync("Executed operation");
        }
        catch (WorkerException e) when (e.Code >= 0 && e.Code < 100)
        {
            await Logger.WriteLineAsync($"Error code {e.Code}");
        }
        catch (WorkerException)
        {
            await Logger.WriteLineAsync($"Unknown error code");
        }
        finally
        {
            await Logger.FlushAsync();
        }
    }
    ...
}

index initializers

public class Logger : IEnumerable, IDisposable
{
    private Dictionary data;

    public Logger()
    {
        data = new Dictionary
        {
            [0] = "Logger has been initialized"
        };
    }
}

Extension methods for collection initializers

public static class LoggerExtensions
{
    public static void Add(this Logger logger, string log)
    {
        logger?.WriteLine(log);
    }
}

[TestClass]
public class LoggerTests
{
    [TestMethod]
    public void Extension_Add_Method()
    {
        const string logItem = "Log Item";
        var logger = new Logger { logItem };
        ...
    }
}

using static

using static Microsoft.VisualStudio.TestTools.UnitTesting.Assert;

[TestClass]
public class LoggerTests
{
    [TestMethod]
	public void Initial_State()
	{
		var logger = new Logger();

		AreEqual(1, logger.Count());
		AreEqual("Logger has been initialized", logger.First());
	}
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s