Pattern matching in C# 7.0

C# 7.0 introduces a new language feature called pattern matching. If you are familiar with F# then you’ll know what pattern matching is about. Pattern matching is used extensively in F# but has not been available in C# before 7.0. Also, pattern matching is not just a simple feature in F#, but more like a wide range of features. However, C# 7.0 has not yet caught up with all that. C# 7.0 only introduces a small set of features behind pattern matching and can be regarded as syntactic sugar, but it’s a good start. I’d expect that the same F# features will eventually be transferred into C# as well in upcoming updates.

Pattern matching is most often used in “if” or “switch” branches to see if an incoming value matches a certain pattern. If it does then we take that path, otherwise we take another.

Let’s start with a starting point with a base class and two derived classes:

Read more of this post

Advertisement

More on deconstruction in C# 7

We looked at deconstruction using the new ValueTuple type in this post. This short post only shows a couple more bits and pieces related to object deconstruction in C# 7.

Consider the following Rectangle class:

public class Rectangle
{
	public int Width { get; set; }
	public int Height { get; set; }
}

Let’s see if we can collect the Width and Height properties into a tuple:

Read more of this post

New Tuple features and deconstruction with Tuples in C# 7

Tuples have been available in C# for some time now. C# 7 comes with a handful of new things for tuples though.

Let’s see an example for using tuples in the old way. The following function returns a Tuple with two integers: the first is the total days of a duration and the second is the total hours of a duration. Not the most useful function that the world has ever seen, but it’s good for demo purposes:

private Tuple<int, int> AnalyseDatesOld(DateTime first, DateTime second)
{
	TimeSpan timespan = (second - first).Duration();
	return new Tuple<int, int>(Convert.ToInt32(timespan.TotalDays), Convert.ToInt32(timespan.TotalHours));
}

Read more of this post

Expression bodied members in constructors and get-set properties in C# 7.0

Expression bodied members were introduced in C# 6 for methods and properties. This feature has been extended to constructors and getters/setters in C# 7.0.

Here’s an example:

public class Dog
{
	private string name;

	public Dog(String name) => this.name = name;	

	public string NameFormatted
	{
		get => name.ToUpper();
		set => name = value.ToUpper();
	}

	public string Name
	{
		get => name;
	}
}

View all various C# language feature related posts here.

Handling out variables in C# 7.0

Most of you will be familiar with “out” variables in C#. They are often misused to return multiple values from a function and can indicate a code smell.

Nevertheless they exist and 7.0 provides some new syntax in this area.

Here’s a typical example from the well-known built-in TryParse function from before C# 7.0:

public void OldWay()
{
	int number;
	if (int.TryParse("1234", out number))
	{
		Console.WriteLine(number);
	}
}

We instantiate “number”, pass it to TryParse and it will be populated with 1234 if the parse succeeds.

C# 7 saves us from the necessity of declaring a variable up front in the following way:

public void NewWay()
{
	//include out param in expression
	if (int.TryParse("1234", out int number)) //works with "var" as well as with the concrete object type
	{
		Console.WriteLine(number);
	}
	Console.WriteLine(number);
}

So we declare “number” in an expression and it will be available outside the “if” block as well.

If parsing fails then the declared variable will get a default value. Numbers get 0, reference types “null” etc.

View all various C# language feature related posts here.

Using delimiters for numeric literals in C# 7.0

Say you need to work with relatively large numbers in your C# code:

int number = 3452123;

Wouldn’t it be nice if you could use some kind of delimiter to indicate the millions, thousands etc? Like in 3,452,123? In C# 7.0 the underscore provides a solution for this:

int number = 3_452_123;

The underscores will be ignored by the compiler.

View all various C# language feature related posts here.

Embedded local functions in C# 7.0

Occasionally it happens that we want to group related code within a function without creating another private function for that. C# 7.0 provides a neat way for that in the form of local functions which are functions within functions.

Consider the following example:

public class LocalFunctionsDemo
{
	public void RunDemo()
	{
		int GetDiff(DateTime first, DateTime second)
		{
			TimeSpan ts = (second - first).Duration();
			return Convert.ToInt32(ts.TotalDays);
		}

                int dayDiff = GetDiff(DateTime.UtcNow, DateTime.UtcNow.AddHours(10));
			
		Console.WriteLine(dayDiff);
	}
}

Read more of this post

Access modifiers in C# 7.2

C# 7.2 comes with a new access modifier “private protected”. It sounds like a weird combination so let’s see how the various access modifiers in the current release of C# work.

Let’s start with an abstract class called Animal:

public abstract class Animal
{
	private String privateName = "Private name";
	protected String protectedName = "Protected name";
	protected internal String protectedInternalName = "Protected internal name"; 
	private protected String privateProtectedName = "Private protected name";
	public String publicName = "Public name";
}

Read more of this post

Async Main methods in C# 7.1

Async methods have the tendency to bubble up to the top of the call chain. Asynchronous repository calls in a large web application are often accompanied by asynchronous methods in the controllers as well.

However, this has until recently posed a problem in Console applications where the “top” function is Main. The Main function, as we all know, must adhere to a small number of rules, one of which being that it must either be void or return an integer in case we care about the exit code. So what could we do if we wanted to call upon an asynchronous method from Main? We couldn’t change its signature unfortunately to make it async so we turned to other ways like calling GetAwaiter().GetResult() on the awaitable method.

C# 7.1 solves this problem by enabling another type of Main method signature:

Read more of this post

Using the ValueTask of T object in C# 7.0

By now probably all .NET developers are aware of the await and async keywords, what they do and how they work.

Here’s a small example where the CalculateSum function simulates a potentially time-consuming mathematical operation:

public class AsyncValueTaskDemo
{
	public void RunDemo()
	{
		int res = CalculateSum(0, 0).Result;
		Console.WriteLine(res);
	}

	private async Task<int> CalculateSum(int a, int b)
	{
		if (a == 0 && b == 0)
		{
			return 0;
		}

		return await Task.Run(() => a + b);
	}
}

Read more of this post

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: