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

Advertisements

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

ultimatemindsettoday

A great WordPress.com 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

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

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: