Learning and Improving Our Code Style with C# 10

Overview

C# (pronounced as "C sharp") is a powerful and versatile programming language developed by Microsoft. As a result of the release of C# 10, developers will have access to even more features and improvements, making it an exciting time to learn and improve our code. Whether we're a seasoned developer or just starting in software development, learning C# can make us more efficient, maintainable, and elegant. Throughout this article, we'll explore some strategies and resources that will help us learn C# 10 and elevate our coding skills.

Get to know the basics

Before diving into the advanced features of C# 10, it's important to have a solid understanding of the fundamentals. Please make sure we are comfortable with concepts like variables, data types, control flow, classes, inheritance, and polymorphism. We can learn these basics effectively using resources like Microsoft's official documentation, online tutorials, and books like "C# Programming in Easy Steps" by Mike McGrath.

In this code example below, the variables are defined for people's age, name, and height. The code then checks whether the individual is an adult (over 18) or a minor (under 18), printing the appropriate message along with their name and height. If the individual is 18 or older, a message indicates that they are an adult; otherwise, a message indicates that they are a minor.

// Variables and data types
int age = 25;
string name = "John";
double height = 6.1;

// Control flow
if (age >= 18)
{
    Console.WriteLine($"You are an adult {name} and your height is {height}.");
}
else
{
    Console.WriteLine($"You are a minor {name} and your height is {height}.");
}

Classes and Inheritance

In the code example below we have a Person and a Student instance created using this code snippet, and their respective properties are set, including name, age, school name, and school e-mail address. Based on whether each object is of type Student or not, it prints out a message indicating their status by using a PersonChecker class. Person and Student define basic personal information, with Student inheriting from Person and adding school-related properties.

using ZiggyRafiq.CodeStyles.Helper;
using ZiggyRafiq.CodeStyles.Models;

//Person Code Example
var person = new Person
{ Name="Tony Walker",
  Age=21
};

var student = new Student
{
    Name = "Lisa Simth",
    Age = 18,
    SchoolName = "Birmingham City High School",
    SchoolEmail = "[email protected]"
};

PersonChecker.CheckIfStudent(person);
PersonChecker.CheckIfStudent(student);
namespace ZiggyRafiq.CodeStyles.Models;
public class Person
{
    public string Name { get; set; } = string.Empty;
    public int Age { get; set; }

}
namespace ZiggyRafiq.CodeStyles.Models;
public class Student:Person
{
    public string SchoolName { get; set; } = string.Empty;
    public string SchoolEmail { get; set; } = string. Empty;

}
using ZiggyRafiq.CodeStyles.Models;

namespace ZiggyRafiq.CodeStyles.Helper;
public static class PersonChecker
{
    public static void CheckIfStudent(Person person)
    {
        Console.WriteLine((person is Student student) ? $"{student.Name} is a student at {student.SchoolName}" : $"{person.Name} is not a student.");

    }
}

Keep up with the latest features of C# 10

There are several new features and improvements in C# 10 - global usings, file-scoped namespace declarations, enhanced pattern matching, and sealed records - which improve performance. To better understand the use and benefits of these features, read the official release notes, blogs, and community discussions. Experiment with these features in our projects to learn more about their benefits and usage.

// Global usings
global using System;

Console.WriteLine("Hello, world! using Global using System example, which is by default part of the console application in C#.");

Principles of clean code

Clean, readable, and maintainable code is crucial for any software project. Implement clean code principles, such as meaningful variable names, proper indentation, consistent formatting, and modularisation. ReSharper and StyleCop are great tools for enforcing coding standards and identifying areas of improvement.

The code example below as the Calculator class defines four arithmetic methods.Add, Subtract, Multiply, and Divide. Each method takes two integer parameters and performs the corresponding arithmetic operation, returning the result. In the Divide method, if the divisor is zero, an ArgumentException with an error message is thrown to prevent division by zero.

Usage of the Calculator class. It creates an instance of a calculator and then performs addition, subtraction, multiplication, and division operations on two integer numbers (num1 and num2). A division by zero is not fatal to the program if it is caught by ArgumentException and printed instead of crashing.

namespace ZiggyRafiq.CodeStyles.Helper;
public class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    public int Subtract(int a, int b)
    {
        return a - b;
    }

    public int Multiply(int a, int b)
    {
        return a * b;
    }

    public int Divide(int a, int b)
    {
        if (b == 0)
          throw new ArgumentException("Divisor cannot be zero.", nameof(b));
        
        return a / b;
    }
}
//Calculator Code Example
var calculator = new Calculator();

int num1 = 10;
int num2 = 5;

// Addition
Console.WriteLine($"Addition: {num1} + {num2} = {calculator.Add(num1, num2)}");

// Subtraction
Console.WriteLine($"Subtraction: {num1} - {num2} = {calculator.Subtract(num1, num2)}");

// Multiplication
Console.WriteLine($"Multiplication: {num1} * {num2} = {calculator.Multiply(num1, num2)}");

// Division
try
{
    Console.WriteLine($"Division: {num1} / {num2} = {calculator.Divide(num1, num2)}");
}
catch (ArgumentException ex)
{
    Console.WriteLine(ex.Message);
}

I am also currently writing a book titled Clean Code using C# 10 A Complete Guide with Code Examples, which will be published here at C# Corner in the coming months. The plan is to publish the book no later than the end of May 2024.

Review code and learn from open-source projects

Our code style can be improved by participating in code reviews and contributing to open-source projects. Working with other developers exposes us to a wide variety of coding styles, best practices, and feedback that can help us refine our skills. Enhance our understanding of C# development practices by participating in discussions, asking questions, and accepting constructive criticism.

Engage in problem-solving activities

Practice problem-solving by coding challenges and exercises on LeetCode, HackerRank, and CodeSignal. Websites like LeetCode, HackerRank, and CodeSignal offer a wide variety of problems categorized by difficulty level. By solving these challenges, we will not only strengthen our algorithmic thinking, but we will also become familiar with the various C# language features and libraries available.

In the code example below, we define a method called Duplicates within a static class Remove, aimed at removing duplicates from an array of integers (nums). As iterates through the array, it identifies unique elements by comparing each to the previous one. A unique element is placed in a new position in the array, and the method returns the modified array's length after removing duplicates in place. By removing duplicates from the numbers array and printing the modified array to the console, the provided code illustrates its use.


//Remove Duplicates Code Example
int[] numbers = { 1, 1, 2, 2, 3, 4, 5, 5, 6 };

int length = Remove.Duplicates(numbers);
Console.WriteLine("Array with duplicates removed:");
for (int i = 0; i < length; i++)
{
    Console.Write(numbers[i] + " ");
}
Console.WriteLine(); 

Console.WriteLine($"Length of the modified array: {length}");
namespace ZiggyRafiq.CodeStyles.Helper;
public static class Remove
{
    public static int Duplicates(int[] nums)
    {
        if (nums.Length == 0) return 0;

        int i = 0;

        for (int j = 1; j < nums.Length; j++)
        {
            if (nums[j] != nums[i])
            {
                i++; 
                nums[i] = nums[j];
            }
        }

        return i + 1; 
    }
}

Learn how to read high-quality code

Insights into effective coding techniques and design patterns can be gained by reading high-quality code written by experienced developers. Take a look at open-source projects on GitHub and study code written by renowned developers. To incorporate similar practices into our projects, analyze their approaches to problem-solving, coding organization, and documentation.

Participate in workshops and conferences

Stay current with the latest trends, tools, and best practices by attending workshops, webinars, and conferences about C# development. We can broaden our understanding of C# by networking with industry professionals and attending technical sessions that inspire us to adopt new techniques. Connect with like-minded individuals by attending local meetups or virtual events hosted by developer communities.

Summary

To master C# 10 and improve our code style, we need dedication, practice, and a willingness to learn. Practicing problem-solving, reading high-quality code, attending workshops, and seeking feedback and mentorship will help us elevate our C# skills and write more elegant and efficient code if we master the fundamentals, stay up to date on the latest features, embrace clean code principles, participate in code reviews, and participate in code reviews. To become a proficient C# developer and make a positive impact on our software projects, start applying these strategies today.

Feedback and mentoring are important

A fresh pair of eyes can often spot issues or suggest optimizations that might have been overlooked. Get feedback from peers, mentors, or experienced developers to gain valuable insight into areas for improvement. We can grow as a developer by finding a mentor who can guide us through our C# learning journey, offer advice, and share our expertise.

Please do not forget to like this article if you have found it useful and follow me on my LinkedIn https://www.linkedin.com/in/ziggyrafiq/ also I have uploaded the source code for this article on my GitHub Repo https://github.com/ziggyrafiq/CSharpCodeStyle


Similar Articles