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


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) => = 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))

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

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));

Read more of this post


A great site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: