Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

5 C# Evolutions You May Not Know

DZone's Guide to

5 C# Evolutions You May Not Know

In this article, we will cover some C# evolutions you may not know and, hopefully, they will help you with your project and development.

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

1. Safe Navigation Operator ( ? Operator):

The ? operator was introduced with .NET 2.0, with the nullable types that allow variables to have null as a value or to not have one at all. We can test it with the HasValue property.
In C# 6, Microsoft added a new feature to this operator (?) called safe navigation operator.

It's so simple and so useful, let me explain it with an example. We access a child property or method via the navigation operator "." but if you try to navigate into a null variable you will have the famous NullReferenceException. So we must test before accessing or calling any method on this object like this : 

// porsche is an instance of a Car Class
if(porsche!=null && porsche.Name !=null)
  console.Write(porsche.Name); // we can use the Name proprety

// If we want to use the Accelerate Methode
if(porsche!=null)
  porsche.Accelerate(10);

With safe navigation we can do this : 

string nom = porsche?.Name ; 

// and to call Accelerate()
porsche?.Accelerate(); 

2. Three Ways to Build a String (String Interpolation): 

  • There are many ways to build a string, The best and faster one, if we want to talk about execution time, is the StringBuilder: 

// Create a StringBuilder that expects to hold 50 characters.
// Initialize the StringBuilder with "ABC".
StringBuilder sb = new StringBuilder("ABC", 50);

// Append three characters (D, E, and F) to the end of the StringBuilder.
sb.Append("DEF");

// Display the string
Console.WriteLine(sb.ToString());
  • If we have some parameter to put in our string we can use the String.Format,like this:

decimal temp = 20.4m;
string s = String.Format("The temperature is {0}°C.", temp);
Console.WriteLine(s);
// Displays 'The temperature is 20.4°C.'

In this method, there are many options to transform your string in a specific format.

You can see all the options in this link

  • The evolution in C# 6 is the new string interpolation syntax:

string name = Joe ;
string hours = "11:00";

Console.WriteLine($"Name = {name}, hours = {hours}");

3. An Elegant Way to Structure an Object (Tuple):

(This is just an example of use)
The majority of programming languages support functions and procedures used with the standard format (a signature, parameters, and a return object). Generally, if we want to return many values or objects, we are obliged to use a list of objects or an array. To do otherwise, C# 6 offered us an elegant structure called a Tuple.

MSDN defines a Tuple as : 

A tuple is a data structure that has a specific number and sequence of elements. An example of a tuple is a data structure with three elements (known as a 3-tuple or triple) that is used to store an identifier such as a person's name in the first element, a year in the second element, and the person's income for that year in the third element. 

There are many ways to create a Tuple.

  • Use the classic constructor, new:

Tuple<string, string,string> person = new Tuple<string, string,string>("Jhon","Doe","5555");
Console.WriteLine("Full Name: {0} {1}  ", person.Item1, person.Item2);
Console.WriteLine("PIN: {0} ", person.Item3);
  • Use The static method, Create:

// Create a 5-tuple.
var population = Tuple.Create("Tunisia", 6999, 54462, 9888, 5258456);
// Display the first and last elements.
Console.WriteLine("Population of {0} in 2013: {1:N0}",
                  population.Item1, population.Item5);
// The example displays the following output:
//       Population of Tunisia in 2013: 5,258,456
  • In C# 7, there is a new way to declare Tuples and get rid of Item1 and Item2 and name them with a significant keyword.

public (string name, string location, string population) GetCountry() {
// fin a person in a list and return
return ("Tunisia","North Africa","5258456") ; 
}

var country = GetCountry(); 

Console.WriteLine("Population of {0} - {1} in 2013: {2:N0}",
                  country.name,country.location, country.population);
// The example displays the following output:
//       Population of Tunisia - North Africa in 2013: 5,258,456

4 . An Enumerable Function's Params:

The params keyword give you the possibility to have a variable method's params number and pass a list of objects in the method call. It's a useful feature when you don't have any idea of the number of objects passed in a parameter. 

public void PrintValues (params string [] values)
{
foreach (var value in values)
  Console.WriteLine(value);
}

PintValues("Hello","this","is","a","test"); 

// Consol print 
// Hello
// this
// is
// a
// test


5. Static Imports:

With C# 6, you can import a dependency with the keyword static. In this way, you can use any method in the imported reference without specifying the class.

using static System.Math;
...
double x = 3;
double y = 4;
double distance = Sqrt(x * x + y * y);

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
.net ,c# ,web dev ,.net application development

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}