#Net5 – C#9 “records” and “deconstruction” super cool feature 🆒🆒🆒

Buy Me A Coffee

Hi !

I’m still learning about C#9, and there is a lot to learn about records. And, between all this information, I Just learn a super cool feature related to records: deconstruction.

Let’s start with a simple record definition for a pet. This one includes pet’s name and pet’s age:

public record Pet
{
    public string Name { get; init; }
    public int Age { get; init; }
    public Pet(string name, int age)
        => (Name, Age) = (name, age);
}

This is fine, init only properties (cool feature!) and we can access the values as usual.

static void Main(string[] args)
{
    var pet = new Pet("Goku", 2);

    // get pet info, standard way
    var gokuName = pet.Name;
    var gokuAge = pet.Age;
}

So far, so good. However, if you like clean code, we can improve this a little using some new features in C#9. So, let’s start with much simpler record definition.

public record NewPet(string Name, int Age);

And we can access the pet properties using deconstruction (new term for me!)

// get pet info, C#9 deconstruction
var newPet = new NewPet("Goku", 2);
var (gokuName, gokuAge) = newPet;

I like this new one 👆 too ! I’ll always like features that improves readability and saves us a lot of extra code.

Happy coding!

Greetings

El Bruno


References


¿Con ganas de ponerte al día?

En Lemoncode te ofrecemos formación online impartida por profesionales que se baten el cobre en consultoría:

#Net5 – C#9 “Init-only properties” are super cool 🆒🆒🆒

Buy Me A Coffee

Hi !

So this one does not fit in the line “readability improvement”, however is a nice step in order to write cleaner code. Yes, I know that doesn’t make sense, let me try to explain.

Let’s start with a simple class with 2 properties. Interesting enough the property Age has a new accessor [init] to describe the property as a read-only property:

class Pet
{
  public string Name { get; set; }
  public int Age { get; init; }
}

When we create a new Pet object, we can set the initial value of Age on the construction of the object (object initialization), and that’s it. Otherwise we will get this amazing error.

Error CS8852 Init-only property or indexer 'Program.Pet.Age' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. 
Csharp9 init only properties

Until C#9, the properties in a class need to be mutable in order to support Object Initialization. And that means some extra code in the property-set definition in order to support read-only properties. Now in C# 9, this is solved with the [init] accessor 😁😁😁

I like this new one 👆 ! Not a great readability improvement, but it saves us a lot of extra code.

Happy coding!

Greetings

El Bruno


References


¿Con ganas de ponerte al día?

En Lemoncode te ofrecemos formación online impartida por profesionales que se baten el cobre en consultoría:

#Net5 – C#9 logical operators “is” and “is not” are super cool 🆒🆒🆒

Buy Me A Coffee

Hi !

In the line of good features, that are also nice to read, the new use of is and is not is a huge improvement in readability.

As usual, old school validation for objects and types:

// old school
if(!(testObj is MyClass)) {...}

And now, we can type the validation with some style:

// C# 9 style
if(testObj is not MyClass) {...}

I like this new one 👆, now null / not null and other validations will be the same. With an improed readability !

Happy coding!

Greetings

El Bruno


References


¿Con ganas de ponerte al día?

En Lemoncode te ofrecemos formación online impartida por profesionales que se baten el cobre en consultoría:

#Net5 – C#9 target-typed new expressions are super cool 🆒🆒🆒

Buy Me A Coffee

Hi !

I know I’m late to the party here, however I’m still enjoying some of the new C# 9 features a lot. I just realized that now, I can create objects in a different way, which is still super clear to read.

Disclaimer: some of the new features are cool, however my gut told me that they will make code harder to read. I also understand that I have 20 years of writing C# code in my back, so I need to find the balance here.

As usual, 2 lines of code are the best way to showcase this:

// old school
var pointOldSchool = new System.Drawing.Point(3, 5);

// new school and still very readable
System.Drawing.Point pointCSharpNine = new(3, 5);

// crappy output
Console.WriteLine("Old School: var pointOldSchool = new System.Drawing.Point(3, 5);");
Console.WriteLine(pointOldSchool);

Console.WriteLine("C#9: System.Drawing.Point pointCSharpNine = new(3, 5);");
Console.WriteLine(pointCSharpNine);

This this output as expected:

Old School: var pointOldSchool = new System.Drawing.Point(3, 5);
{X=3,Y=5}
C#9: System.Drawing.Point pointCSharpNine = new(3, 5);
{X=3,Y=5}

I like this new one 👆

Happy coding!

Greetings

El Bruno


References


¿Con ganas de ponerte al día?

En Lemoncode te ofrecemos formación online impartida por profesionales que se baten el cobre en consultoría:

#Podcast – NTN 76 – Feliz Año Nuevo 🎉 con todas las novedades de #Net5 !

Buy Me A Coffee

Buenas!

Feliz Año Nuevo 🎉🎉🎉, empezamos el año dando un repaso a todas las novedades de Net 5 con el gran amigo Miguel Teheran. Comentamos un poco la historia de Net y como Net 5 es el primer paso para la unificación de todos los .Net Frameworks que conocemos.

También hablamos un poco de los lenguajes, de las novedades de C#9, del estado de F# y del pobre VB.Net, donde todos coincidimos que está un poco abandonado.

Gracias y felices fiestas !

Speakers

  • Miguel Teheran es Developer and Software Consultant (LinkedIn)
  • Juan Carlos Quijano Abad es Microsoft Certified Trainer, Arquitecto de Soluciones en Azure, Consultor independiente en implantación de DevOps (LinkedIn)
  • Bruno Capuano es Canada Innovation Lead at Avanade and Microsoft AI MVP (LinkedIn)

Ir a descargar

Resources

Happy coding!

Greetings

El Bruno



¿Con ganas de ponerte al día?

En Lemoncode te ofrecemos formación online impartida por profesionales que se baten el cobre en consultoría:

#Net5 – C#9 “records”, “with” and “this”, a super cool mix 🆒🆒🆒

Buy Me A Coffee

Hi !

Our next podcast episode is focused on .Net 5. We had an amazing chat around a lot of features, and of course, C# 9 was part of the conversation.

I got this amazing post [C# 9.0: Records – Work With Immutable Data Classes] from Tomas Huber, in my reading notes and working with records is something that I wanted to test.

In a few words, a record is an immutable class. Which is super cool, because it allows some cool operations for mapping, reflection and more. Again, please read Tomas post.

On of the features of records is that once, you define a record with a constructor, there is no default constructor anymore. Let’s start with a simple person record with 3 properties for Name, Age and Married status (as boolean)

public record PersonRecord(string Name, int Age, bool Married)
{
    public override string ToString() => 
        $"Name: {Name} - Age: {Age} - Married: {Married}";
}

Losing the default constructor can be a challenge if we want to copy a record. However we can take advantage of the with expression and create new objects that uses the protected copy constructor. Let’s take a look at the same person object with a CopyUsingMarriedTrue() function that, creates a new object with the same properties changing the value of the Married property.

public record PersonRecord(string Name, int Age, bool Married = false)
{
    public Guid Id { get; init; } = Guid.NewGuid();
    public override string ToString() => 
        $"Name: {Name} - Age: {Age} - Married: {Married} - Guid: {Id}";

    public PersonRecord CopyUsingMarriedTrue() => this with { Married = true };
}

Now it’s time for a full Console test, where I create a couple of persons and check the values of the person. Important, I added a Guid Id property to test the copy and constructor behavior.

  • Lines 14 to 18, I created a Bruno person with Married as True, and I created a BrunoMarried to check the new created object.
  • Lines 20 to 25, I created a Valentino person with Married as False and I created a ValentinoMarried to check the new created object.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("start");
var bruno = new PersonRecord("Bruno", 40, true);
Console.WriteLine($"{bruno.ToString()}");
Console.WriteLine($"Bruno Is Married created");
var brunoMarried = bruno.CopyUsingMarriedTrue();
Console.WriteLine($"{brunoMarried }");
Console.WriteLine($"———————————–");
var valentino = new PersonRecord("Valentino", 13, false);
Console.WriteLine($"{valentino.ToString()}");
Console.WriteLine($"Valentino Is Married created");
var valentinoMarried = valentino.CopyUsingMarriedTrue();
Console.WriteLine($"{valentinoMarried}");
}
}
public record PersonRecord(string Name, int Age, bool Married = false)
{
public Guid Id { get; init; } = Guid.NewGuid();
public override string ToString() => $"Name: {Name} – Age: {Age} – Married: {Married} – Guid: {Id}";
public PersonRecord CopyUsingMarriedTrue() => this with { Married = true };
}
}

The output is an awesome surprise. I mean, my code always surprise me, however using this feature is an awesome surprise !

start
Name: Bruno - Age: 40 - Married: True - Guid: 82e60022-0fb2-456d-89c0-ab88bef5aff6
Bruno Is Married created
Name: Bruno - Age: 40 - Married: True - Guid: 82e60022-0fb2-456d-89c0-ab88bef5aff6
-----------------------------------
Name: Valentino - Age: 13 - Married: False - Guid: 7acca9e2-f461-4fc9-8e29-06f6f0ffb6c6
Valentino Is Married created
Name: Valentino - Age: 13 - Married: True - Guid: 7acca9e2-f461-4fc9-8e29-06f6f0ffb6c6
csharp 9 with and records

Happy coding!

Greetings

El Bruno


References


¿Con ganas de ponerte al día?

En Lemoncode te ofrecemos formación online impartida por profesionales que se baten el cobre en consultoría:

#AI – #Lobe, exporting to ONNX, and running in C# #csharp @lobe_ai

Buy Me A Coffee

Hi !

Follow up post after yesterday post on Lobe, and today focusing on ONNX and C# code. And, it all started because someone asked in twitter about an ETA to export the model to ONNX

I decided to give a try to the TensorFlow to Onnx tool, and it worked great ! (see references). I use the following command to convert my model

python -m tf2onnx.convert --saved-model model --output model.onnx

From the PB exported model from yesterday, and I got my 2 models

And, here I got an amazing surprise. Before I started to write some C# code, I found some NuGet packages available to use

  • lobe
  • lobe.Onnx
  • lobe.ImageSharp
lobe 100 install nuget packages

And, after a quick search I found some sample code in GitHub about how to use these packages. So, I pickup the original Code and make a few changes to perform estimations on 2 manual drawings.

Remember my model was trained to analyze drawings and detect: humans, fish and flowers.

I created a new C# Console App and

  • copy the generated [model.onnx]
  • copy the 2 test files: [fishy.png] and [human.png]
  • copy the original [signature.json] file generated on the Lobe TensorFlow export

I edited the [signature.json] file and change the values

  • format to onnx
  • filename to the generated exported filename

And I was ready to run my code:

using System;
using System.IO;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using lobe.ImageSharp;
using lobe;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var signatureFilePath = "signature.json";
ImageClassifier.Register("onnx", () => new OnnxImageClassifier());
using var classifier = ImageClassifier.CreateFromSignatureFile(
new FileInfo(signatureFilePath));
// Images
ShowResults("fishy.png", classifier);
ShowResults("human.png", classifier);
}
private static void ShowResults(string imagePath, ImageClassifier classifier)
{
var results = classifier.Classify(Image
.Load(imagePath).CloneAs<Rgb24>());
Console.WriteLine();
Console.WriteLine($"Image : {imagePath}");
Console.WriteLine($"Top Label: {results.Classification.Label}");
foreach (var res in results.Classifications)
{
Console.WriteLine($" – Label: {res.Label} – Confidence: {res.Confidence}");
}
}
}
}

And the output is fast and great, as we are used to do with Onnx

Lobe looks great !

Happy coding!

Greetings

El Bruno


References

#Coding4Fun – Sorting Arrays in #JavaScript, #Python and #CSharp … choose your own adventure

Buy Me A Coffee

Hi !

Not my usual set of posts, however this keep me thinking a lot. It all started with this tweet; an usual joke about JavaScript, and how it works with types.

array sorting in Javascript

I noticed that some responses focused on the “you need to know how the language works” before posting this. And it is correct, you need to know how JavaScript converts the elements into strings and then sort, to understand the crappy not so accurate output.

However, I am not a JavaScript expert, and I do not want to be one. And, when I use a tool or a programming language, I expect to have a nice learning curve; the previous example is not a nice “Welcome to JavaScript, where arrays and type conversions will make you think twice until you get it!”.

I’ve been doing a lot of Python programming, so I did the same exercise, and it worked as you may expect !

array and sort in python

I also did a similar in C#, and it also worked !

array and sort in C#

Do not get me wrong, this is not an Anti-JavaScript post. JavaScript is awesome and is almost everywhere. I know a lot of awesome JavaScript programmers, who I really admire.

However as a developer, I expect to avoid something simple like an array sort issue. I will always focus on “the code is clean and everyone will understand how it works, just read the code!”.

I am used to this as a C# developer; and I also found that Python is cool for this. But, sometimes, just sometimes, JavaScript looks like hell !

Bonus: An old post in my last JavaScript adventure.

Happy coding!

Greetings

El Bruno


#Net – Learning C # using only a browser

Hi!

A few days ago, at a university, one of the attendees in a session asked me what was the best way to learn C#. As always, this question depends on the level of the person who wants to learn, although it has served as an excuse to see what’s new in the .Net ecosystem.

Well, in addition to the (now) classic Microsoft Docs, I found a resource that is rather interesting

.NET In Browser tutorial

The format is rather simple, a small tutorial on basic concepts of C #, a web code editor and the chance to compile and see the result on the same web.

I1

As entry point for concepts such as handling of strings, arrays, etc. it seems like a good starting point to start.

Greetings @ Burlington

El Bruno

References

#Net – Aprendiendo C# utilizando solo un navegador

Buenas!

Hace unos días, en una universidad, uno de los asistentes en una sesión me pregunto cual era la mejor forma de aprender C#. Como siempre esta pregunta depende del nivel de la persona que quiere aprender, aunque me ha servido de excusa para ver que hay de nuevo en el ecosistema .Net.

Pues bien, además de los clásicos Docs, he encontrado un recurso que es más bien interesante

.NET In Browser tutorial

El formato es mas bien simple, un pequeño tutorial sobre conceptos básicos de C#, un editor web de código y la capacidad de compilar y ver el resultado en la misma web.

I1

Como punto de entrada para conceptos como manejo de strings, arrays, etc. me parece un buen punto de partida para comenzar.

Saludos @ Burlington

El Bruno

References