DEV Community

loading...
Cover image for C# Tips and Tricks - Part 1

C# Tips and Tricks - Part 1

Mohamad Lawand
Code is Life. Crossfitter. Technical Architect. Just another human walking the earth! https://youtube.com/c/mohamadlawand
・5 min read

In this article we will be covering:

  • String interpolation
  • Discards

You can watch the full video on YouTube

You can find the source code on GitHub
https://github.com/mohamadlawand087/v32-CodeTipsTricks-Ep1

String Interpolation

This is a really powerful feature that empower C# developers to be more productive. The most standard way of outputting text is

// This is a very standard way of outputing text
Console.WriteLine("Hello Mohamad!");
Enter fullscreen mode Exit fullscreen mode

What happens now if i want to change the name of the person so instead of Mohamad i want to say "Hello John" or "Hello Mickey".

We have a couple of options to accomplish this

1- Manually updating the string values with the name that we want, but this is not a flexible way of accomplishing this result

2- Utilising string formatting so we can do something like this

var name = "Mohamad";
var outputText = string.Format("Hello {0}", name);
Console.WriteLine(outputText);
Enter fullscreen mode Exit fullscreen mode

But we can see it has some weird formatting when specifying where the name should be in the string, and for example if we want to add another name we need to do something like this

var name = "Mohamad";
var name2 = "John";
var outputText = string.Format("Hello {0} {1}", name, name2);
Console.WriteLine(outputText);
Enter fullscreen mode Exit fullscreen mode

And we can see how it starts to get complicated as we add more information and we try to customise more and more.

The outcome that we want to reach is to make the string output as easy and understandable as possible so what we want is to replace the 0, 1 .... with the actual values that we want to add to the string. So the way we can accomplish this is by string interpolation.

so we want to have something like this

Console.WriteLine("Hello {name}"); // Outcome: Hello {name}
Enter fullscreen mode Exit fullscreen mode

But when we run this, we don't get the value we want we get "{name}" instead of the value, thats because string interpolation is not enabled. How do enable it by adding a $ to our string, so it will be something like this

Console.WriteLine($"Hello {name}"); // Outcome: Hello Mohamad
Enter fullscreen mode Exit fullscreen mode

The $ tells the compiler that there string interpolation and it needs to get the value of the variables and insert them in the string. So basically we are embedding the variable into our strings.

Now if i have 2 or more variables i can do something like this

Console.WriteLine($"Hello {name} & {name2}"); // Hello Mohamad & John
Enter fullscreen mode Exit fullscreen mode

Basically we can utilise string interpolation any way we see fit in our code.

As well we can extend this by utilising inline methods so lets say i want to make the values upper case for name2 we ca do somethinkg like this

Console.WriteLine($"Hello {name} & {name2.ToUpper()}"); // Hello Mohamad & JOHN
Enter fullscreen mode Exit fullscreen mode

String interpolation will make our code more readable and easily understandable.

Now lets say i have a more complex scenario of string output that i want to accomplish something like this

class Car
{
    public string Brand { get; set; }
    public string Color { get; set; }
    public string Engine { get; set; }
    public int Year { get; set; }
    public double Price { get; set; }
}
Enter fullscreen mode Exit fullscreen mode
Car car = new();
car.Brand = "Jeep";
car.Color = "Grey";
car.Engine = "V8";
car.Year = 2015;
car.Price = 19500.25;

var carInfo = $"The {car.Brand}, "
            + $"of color {car.Color} "
            + $"made in {car.Year} "
            + $"is worth £{car.Price} "
            + $"on {DateTime.Now:d}";

Console.WriteLine(carInfo);
// he Jeep, of color Grey made in 2015 is worth £19500.25 on 05/06/2021
Enter fullscreen mode Exit fullscreen mode

As we can see we can customise our output very easily, and make the code more readable and easier to maintain.

Now let us see how we can apply some logic inside the string interpolation, so let us say we want to add some conditioning to see if the price of the car was good or not what we can do is following

var carInfo = $"The {car.Brand}, "
              + $"of color {car.Color} "
              + $"made in {car.Year} "
              + $"is worth £{car.Price} "
              + $"on {DateTime.Now:d} "
              + $"this is a {(car.Price < 20000 ? "low" : "high")} price ";

// The Jeep, of color Grey made in 2015 is worth £19500.25 
// on 05/06/2021 this is a low price
Enter fullscreen mode Exit fullscreen mode

Adding the ( inside the brace will allow us to execute logic to further customise our output

Now lets say you want to use a brace in our string we can use the double brace so it would be something like this

Console.WriteLine($"Hello {{ {name} }} "); // Hello { Mohamad }
Enter fullscreen mode Exit fullscreen mode

The double brace will tell string interpolation to ignore the brace.

Default Literal Expressions

We Can use the default literal to produce the default value of a type when the compiler can infer the expression type. The default literal expression produces the same value as the default(T) expression where T is the inferred type. You can use the default literal in any of the following cases:

  • In the assignment or initialization of a variable.
  • In the declaration of the default value for an optional method parameter.
  • In a method call to provide an argument value.
  • In a return statement or as an expression in an expression-bodied member.

They are enhancements on default value expressions, its a simplifications on how we can utilise it.

// Old Syntax
Func<string, bool> whereClauseOld = default(Func<string, bool>);

// New Syntax
Func<string, bool> whereClauseNew = default;
Enter fullscreen mode Exit fullscreen mode

for a more advance example we can do something like this

T[] InitialiseArray<T>(int length, T initialValue = default(T))
{
    if(length < 0)
     return default(T[]);

    var arr = new T[length];
    for(var i = 0; i < length; i ++)
    {
        arr[i] = initialValue;
    }

    return arr;
}

// Display array
void Display<T>(T[] values) => Console.WriteLine($"[ {string.Join(", ", values)} ]");

Display(InitialiseArray<int>(3)); // output [0,0,0]
Display(InitialiseArray<bool>(4, default(bool))); // output [false, false, false, false]

Complex fillValue = default(Complex);
Display(InitialiseArray(3, fillValue)); // [ (0, 0), (0, 0), (0, 0) ]
Enter fullscreen mode Exit fullscreen mode

Discards

They are temporary dummy variables which are read only we cannot write to them, they are useful when we dont need to know the value of the variables.

This will help with saving memory allocation . They enhance readability and maintainability of the code.

// Discards

// Example 1
var carBrand = "Jeep";
var fromYear = 1960;
var engine = "v8";

var (_, _, price, mileage, _, _) = GetCarInformation(carBrand, fromYear, engine);

Console.WriteLine($"Car info, Model {fromYear} Engine {engine} \n Price {price} Mileage {mileage}");

(string, double, int, int, int, int) GetCarInformation(string name, int year, string engine)
{

    if (name == "Jeep")
    {
        return (name, 0, 35000, 130000, 0, 5);
    }

    return ("", 0, 0, 0, 0, 0);
}

// Example 2
string[] dateStrings = {"05/01/2018 14:57:32.8", "2018-05-01 14:57:32.8"};

foreach(string dateString in dateStrings)
{
    if(DateTime.TryParse(dateString, out DateTime result))
        Console.WriteLine($"'{dateString}': valid");
    else
        Console.WriteLine($"'{dateString}': invalid");

    if(DateTime.TryParse(dateString, out _))
        Console.WriteLine($"'{dateString}': valid");
}

Enter fullscreen mode Exit fullscreen mode

Thank you for reading, please ask your questions in the comments :)

Discussion (2)

Collapse
mdirashid profile image
Md Ibrahim Rashid

Dear Mohamad, It is explained in very easy way. Thanks for writing.

Collapse
justjordant profile image
Jordan Taylor

Hey, great content. I really liked how how you broke down each section and showed how they can be used and advanced. Cheers! ☺