Mastering C# – Pattern Matching

Microsoft has a wonderful tutorial on pattern matching, in which you model a lock (to raise or lower a ship when there would otherwise be a waterfall). They model the two doors and the water level.

While their example is excellent it is long, and in this blog post I’m going to take the essence of pattern matching using their example.

Continue reading
Posted in C# 12, Mini-Tutorial, Programming | Leave a comment

Modern C# Part 3 – Switch Expressions

I admit it, I’ve struggled with pattern matching. In the next few blog posts I’ll explore this magic, starting today with switch expressions (not to be confused with switch statements).

Continue reading
Posted in C#, Mini-Tutorial | Leave a comment

Modern C# Part 2 – Accessing via Implicit Index

Until now, if you wanted to access the last item in a list you had to use a slightly cumbersome syntax. C# 13 introduces the “hat” operator (^) where ^1 is the last element in your collection, ^2 is the penultimate member, etc.

Like many things, this is best illustrated with an example. In the following code I create a simple Person class and initialize a list<Person> with three people (persons?)

 internal class Program
 {
    static void Main(string[] args)
    {
       var tester = new Tester();
       tester.Test();
    }
 }

 public class Tester()
 {
    public void Test()
    {
       var john = new Person { Name = "John", Age = 25 };
       var jane = new Person { Name = "Jane", Age = 30 };
       var joe = new Person { Name = "Joe", Age = 35 };
       var people = new List<Person> { john, jane, joe };      
    }
 }

 public class Person()
 {
    public string Name { get; set; }
    public int Age { get; set; }
 }

Straight forward. Now, if I want to access the last person in this list I can write

 var lastPerson = people[^1];
 Console.WriteLine($"Last person is {lastPerson.Name} who is {lastPerson.Age} years old.");

As you can see, this is concise and easy to understand. You read it as “lastPerson is equal to one back from the end of people.” Let’s run it:

Last person is Joe who is 35 years old.

That is all there is to it. Easy to use and somewhat helpful in simplifying your code.

Posted in Programming | Tagged , | Leave a comment

Modern C# – Part 1

This short post will kick off a series covering some of the new features in C#.

One small but much requested feature is the ability to use any kind of collection for params. Previously you had to pass in an array:

   public void MyMethod(int firstParam, params string[] otherParams)
   {
      foreach (var param in otherParams)
      {
         Console.WriteLine(param);
      }
   }

But now you can pass in any kind of collection,

 public void MyMethod(int firstParam, params List<string> otherParams)
 {
    foreach (var param in otherParams)
    {
       Console.WriteLine(param);
    }
 }

This can save a great deal of fussing, converting your collection to an array and back.

Please note that this is a preview feature. Fortunately, Intellisense will convert your project for you. When you put this in you’ll get the dreaded red squiggly. Click on the light bulb and let it convert your project. Hey! Presto! it works.

We’ll look at a few bigger features in coming blog posts.

Posted in C#, C# 12, Essentials | Leave a comment

Would this book be of interest to you?

I sense that a lot of us have had trouble keeping up with the rapid growth of C# features. My guess is that most of us fell off the cliff somewhere around C# 7 (we’re up to 13/14). I have in mind to write a book that assumes you are already a C# programmer and brings you up to speed on the latest features and techniques.

Here are just a few topics I’d cover:
1. Switch Expressions
2. Pattern matching
3. Tuples
4. Records
5. Dynamic binding

I would not cover such topics as if statements, etc., nor even basic polymorphism.

The book would be as short as possible, providing hands-on examples but no fluff. Further, I wuld not show the evolution of a feature, but rather just teach the most modern version.

Would such a book be of interest to you? I’d like to get a sense of the audience before starting.

Please send me a note at jesseliberty@gmail.com

Posted in C# | Leave a comment

A Dozen Programmer Utilities

Two years ago, I made a list of my indispensable tools. Here is a quick updated version:

Lists are always subjective, but it is helpful, I think, to exchange favorites now and again. Feel free to add yours to the comments. Here’s my list in no particular order

  1. Visual Studio 2022 – goes without saying that this is the world’s best IDE for .NET developers. I use it 8-12 hours a day, it just keeps getting better, especially with CoPilot.
  2. Copilot – AI done right. Integrated with Visual Studio, this add-on is the most powerful and useful tool I have. It can get in the way a little, but when it does its stuff, watch out. Point it at a class and ask for documentation and/or unit tests and watch it go! But kids, don’t try this at home — it needs adult supervision.
  3. ExamDiffPro – there are lots of comparison/merge utilities. Get a good one.
  4. Tweaks by Mads Kristensen — small but very valuable addition to VS
  5. Viasfora – I can not believe how useful this is. Matches braces by color and in any “real” application, this can save a lot of time.
  6. Evernote: I use it to log everything I do, including every fix for recurring issues. It is quick, powerful, and easy to use. Although it has limitations, overall, I’ve found it helpful and reliable.
  7. LastPass – my password manager. I’d be lost without it. (1Password may be better, our mileage may vary)
  8. Git Diff Margin – if you use Git you’ll want to Git this. See what changed in the margin
  9. DB Browser for SQLite – If you are using SQLite, this is a must-have.
  10. BlueSky – the single best social media site for .NET programmers

Note that nearly all of these are free. I do remember the days when a program like Lotus 123 cost something in the hundreds of dollars. It makes me laugh when I see people look at an app and say, “$4, naah, too expensive.”

I am not affiliated with any of these.

As I say, grab these, and if there are others that you use, please note them in the comments.

Thanks

Posted in Essentials | 7 Comments

Where’d it go?

My cache blew up my site. The good people at GoDaddy fixed me up, but I lost a good bit of the past 12 years of content (through my own stupidity). Never fear, however, all the new stuff is intact.

In addition, I took the opportunity to upgrade, so the site should be faster and backed up daily, and while I was at it, we upped the security. So, all in all, there was a silver lining.

Posted in Essentials | 1 Comment

API #9 – Tables

An important part of creating APIs is interacting with data storage. While you can use any number of database programs, a common way to store simple data is in data tables. This is particularly useful when you are recording API calls as part of your telemetry.

Storage tables are not inherently relational. The goal is to keep storage tables simple. This makes them ideal for keeping lists, logging, creating progress entries, and so forth.In this demo, we’ll create a storage table that tracks exceptions thrown during execution of our program. Let’s create a console app that just throws exceptions every few seconds.

Continue reading
Posted in Essentials | 3 Comments

1,000,000 Views!

jesseliberty.com just crossed 1MM views (lifetime). So pleased you’ve stuck with me. See find me in menu to continue the dialog.

Posted in Essentials | Leave a comment

Programming APIs Book

Available now on Amazon
or your favorite neighborhood bookstore.

Posted in Essentials | 10 Comments

Mads Torgersen and C# 13

Mads Torgersen, lead designer of C# joins me to talk about what’s new in C# 13 and much more

Posted in Essentials | Tagged | 2 Comments

Creating APIs Part 8: Validation

Performance is king (well, after accuracy) in APIs. Sending a request to the Database only to discover that the request is invalid is a waste of resources. Thus, we want to validate the request as soon as it hits the endpoint.

FluentValidation is a great tool for creating validators. It installs as a NuGet package. Also grab the version for ASP.Net.

To get going, add a using statement. 

Using FluentValidation 

Next, create a class that derives from AbstractValidator. 

public class CarNotDeletedValidator : AbstractValidator<Car> 

This example uses the Car class from my forthcoming book Creating .NET APIs with C#.

Put your validation rules in the constructor. Each rule is created by using the keyword RuleFor and a lambda expression that indicates which property you want to validate and the validation rule.

using Cars.Data.DTOs; 
using FluentValidation;
namespace Cars.Validators
{ 
    public class CarNotDeletedValidator : AbstractValidator<CarDto> 
    { 
        public CarNotDeletedValidator() 
        { 
            RuleFor(x => x.Is_Deleted).Equal("0"); 
        } 
    } 
}
The Equal operator is one of many that you can find at the FluentValidation documentation page: https://docs.fluentvalidation.net/en/latest/built-in-validators.html

We’ll test the data and then either compare it to what is valid and return an error if appropriate, or, more commonly, we’ll throw an exception if the data fails validation. 

Assuming that it passes validation we can continue to the Database. If however it fails, we can return a meaningful error to the sender.

Posted in Essentials | 2 Comments