C#, Tech

C# 8 features – part 3 (Index type, Recursive pattern, tuned Switch expression => recipe for getting new friends)

This is the last post about C# 8 planned features and today I will write about Index type, recursive pattern and changes in switch construction. I will also teach you how to make new friends while programming. I hope you will not argue, that reading this post will pay off ;).

Index type

Imagine you have an array of some type, for example integers.

int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

Every time you want to access the element that sits at the 2. position from the array’s end, you call array’s length and do some extremely sophisticated 😉 calculation:

Console.WriteLine(a[a.Length – 2]);

Microsoft comes here for the rescue, offering us an Index type that can be coded like this:

Console.WriteLine(a[^2]);

Syntax sugar but I love sweets so will probably use it ?.

Nice picture, huh? Did I regain your attention ;)? Great, because I just wanted to emphasize that in the code above it was not mentioned explicitly, but there is an Index type used. So take a look at the below code which in fact is sugared sugar (it’s never too late to became a diabetic!).

Index i5 = 5;
Index i2fromEnd = ^2;

Console.WriteLine(a[i5]);        //will write 5 on console
Console.WriteLine(a[i2fromEnd]); // will write 8 on console.

 

Ranges

If you still don’t feel the need for adding separate type to just access an array item, think of separating a range of an array by just passing indexes of the first and the last item in the [] brackets. Here comes an example:

var separatedArrayPart = a[i5.. i2fromEnd]; // will return { 3, 4, 5, 6, 7 }

BTW you noticed the ‘..’ between Index objects, don’t you?

Recursive patterns

Let’s say recursive pattern is just ‘C# 7 pattern matching’ continuation. But only more complicated-looking. You know, when you write this code, half of your coworkers (who don’t read such brilliant blogs like mine… N00bs!) will not understand it. They will start googling but there is no explicit C# keyword to google so in the end they will not find out what this construction does. Haha! And here your role appears – they will come to you to ask you ‘what the fuck did you write here?’ and that’s just a tiny step from gaining new friends. Lots of new friends. Awesome, isn’t it? You thank me (or Microsoft) later :P.

So let’s take look at the below code:

foreach (var pet in Pets)
{
   if (pet is Dog { Vaccinated: false, Name: string name })
   {
      Console.WriteLine($"We need to vaccinate {name}");
   }
}

We iterate through the list of Pets and if a pet is of a Dog type with property Vaccinated set to ‘false’, we select this pet name and store it in the ‘name’ variable. Then we write this name on the console, of course.

So if you are a boring unsocial person who doesn’t want to talk to other people, you can always write code like the one below. But to be honest, who would give up on gaining such a popularity in the company? WHO?! ?

foreach (var p in Pets)
{
   if (p is Dog && p.Vaccinated == false)
   {
      Console.WriteLine($"We need to vaccinate {p.Name}");
   }
}

 

Switch expression

You know, if you still think you have too little friends after using recursing pattern in your production code, you can still make something about this. I present you the tuned ‘switch’ construction, ‘Mrs/Mr-The-Hottest-Programmer-In-The-Company’.

var discount = clientX switch
{
   RegularCustomer _ => 0, //(1)
   NewCustomer r => r.Age * 0.05, 
   CustomerWithSpecialCard c => Math.PI * r.Age * 0.15, 
   _ => throw new UnknownFigureException(figure) //(4)
};

 

So, this code is so pretty I don’t know how to start. And I turned off the sarcasm here… Mostly :P.

  • It returns the result of calculation that happens inside each ‘switch-case’ and assign it to the discount variable
  • It makes c# 7 pattern matching (which means checking what type clientX is and then choosing the appropriate ‘case’)
  • It uses arrow like
    X => doSmth();

    instead of

    case X { doSmth ();}
  • It allows us omit naming variable where we don’t need it (look at line (1) in the above code)
  • We can use ‘_’ instead of ‘default’ (line (4) ).

 

My feelings

Here ends our adventure with discovering C# 8 planned features. To be honest I like most of the changes… And at the same time I am a little scared how much the syntaxt evoluates so if you just take a 1-2 year break and come back to C#, you should expect some frustration while reading the code, at least at the begining… But changes are good and IT is quit used to them so it’s gonna be OK ;).

I hope I haven’t done many mistakes in code micro-samples I pasted but if I do – forgive me ;). I hope to test them in a real environment by the end of this year, when C# 8 will officialy appear. But if you want to be 100% sure that you are learning from the good source of knowledge, take a look at Microsoft post here.

 

Photo that makes me hungry by Patrick Fore on Unsplash
Featured photo by frank mckenna on Unsplash

Share this: