The C# Definitive Guide
17 Nov 2018 #tutorial #csharpAre you looking for a learning path to be “fluent” in C#? This is the right place for you! This is my definitive guide to what every beginner and intermediate C# developer should know.
Every intermediate C# developer should know how to productively work with Visual Studio or Visual Studio Code, use async/await keywords, most common LINQ methods and regular expressions. Also, to get around large codebases and be aware of the latest C# features.
1. Environment
Visual Studio is the de-facto Integrated Development Environment (IDE) for C#. Since we will spend most of our workdays with Visual Studio, we should setup Visual Studio to make use more productive.
- Find a colorscheme. For example, I prefer the Solarized theme
- Learn the basic shortcuts:
Ctrl + Shift + b
: Build our solutionCtrl + ,
: Navigate to any method in our solutionCtrl + .
: Apply a refactor or any action in the current code blockCtrl + q
: Search and execute settings or menus of Visual StudioCtrl + Shift + F12
: Go to the next error
- Install some plugins to make our life easier. Like,
- Productivity Power Tools
- Auto Save: No more
Ctrl + S
to save our files - AddNewFile: We can use
Alt + F2
to add one or more files with a single shortcut - VsVim: To bring Vim to Visual Studio. You don’t know Vim? C’mmon!
- Wumpf Solution Color: To color the Visual Studio menu bar based on a folder. Don’t mess with the wrong environment code.
- VS Color Output: To make the Output tab colorful.
- Use C# Interactive. We don’t have to create a dummy Console project to try things out. With C# interactive, we have a C# REPL at our disposition. We can load a NuGet package, a dll, or a C# script (.csx file). From Visual Studio, head to View Menu, Other Windows and click C# Interactive.
For more settings and extensions, check my Visual Studio setup for C#.
2. Git and Github
Git
Git is a version control system. A time machine to go back in time, create alternate stories from a point in time and make alternate stories join our present. You got the analogy?
If we are creating a zip file with our code and naming it after the date of our latest change, Git is a better way.
- Install Git locally
- Learn the basic commands:
init
,add
,status
,commit
,push
- Learn to use Git inside Visual Studio
- Read my beginner’s guide to Git and GitHub
GitHub
Programming is about collaboration. GitHub is the social network for programmers.
With GitHub, we can show our own code, ask for new features in a library, and report bugs in the software we use.
Microsoft, Facebook, Google have some of their own code available on GitHub.
- Check Udacity GitHub course
3. Design Patterns and Object-Oriented Design Principles
Desing patterns are recipes to solve common problems in code. This is, given a certain problem, there is a blueprint or an outline that will help us to solve that problem.
- Recognize some of the most common patterns and learn to use them. For example: Factory, Builder, Composite, Command, Template, Strategy, Null Object, Adapter.
- Check my take on the Decorator and Pipeline patterns.
- Learn Uncle Bob’s SOLID principles.
4. Dealing with large codebases
Programming is also about reading code. Get used to navigate throught large codebases.
- Find a library or a tool you have already used or you find useful. For example, DateTimeExtensions, ByteSize, Insight.Database
- Where are the unit tests? Do they follow a folder structure? Identify a naming convention for them
- Does the project follow certain code convention? For example, are braces written on the same line?
- Grab a copy and compile it yourself
- Debug a test case scenario for a feature you would like to know about
- Find out how a feature was implemented
For more guidelines about reading code, check Changelog’s One sure-fire way to improve your coding.
5. Unit tests
A unit test is a “safety net” to make sure we don’t break things when we add new features or modify our codebase. A unit test is a piece of code that uses our code base from a “user” point of view and verifies a given behavior.
- Read my Unit Testing 101 to get started writing unit tests with C# and MSTest
- Learn what unit test really means. Read Roy Osherove’s Unit Test Definition
- Learn a test naming convention. I compiled these four test naming conventions
- Watch Roy Osherove’s Understand Test Driven Development
- Write some unit tests for some parts of your codebase or practice writing unit tests for a library you know
- Read my takeaways from The Art of Unit Testing
6. LINQ
Language-Integrated Query, LINQ, is the declarative way to work with collections in C# or anything that looks like one. Instead of writing foreach
, for
or while
loops to work with collections, let’s give LINQ a try.
- Learn about lambda expressions. Read my take on the difference between Func and Action
- Check my quick guide to LINQ with examples
- Learn the most frequently used LINQ methods:
Where
,Select
,FirstOrDefault
,Any
, andGroupBy
.
7. Regular Expressions
Have you ever used *.txt
in the file explorer to find all text files in a folder? If so, we have already used regular expressions. But, *.txt
is just the tip of the iceberg.
Regular expressions give us a search syntax to find patterns of text in a string. For example, to find all phone numbers like this one (+57) 3XX XXX-XXX
, let’s use (\(\+\d{2}\))\s(\d{3})\s(\d{3})\-(\d{3})
.
- Learn the basics
- Character sets:
[]
and[^]
- Shorthand:
\d
for digits,\w
for alphanumeric chars,\s
for whitespace. - Repetions:
*
,?
,{min,max}
- Any character: the dot
.
- Escape reserved characters:
^$()[]\|-.*+
- Groups
- Character sets:
- Learn how to match and replace a regex in C#. Take a look at
Match
,IsMatch
,Replace
methods inRegex
class. - Learn how to acess named groups in C#
- Read Regular expressions’ Quickstart
8. async/await
Asyncronous code is code that doesn’t block when executing long-running operations.
- Learn the flow of control of a method marked with
async
andawait
. Read Stephen Cleary’s async and await - Await your code all-the-way-down to avoid deadlocks. Read Don’t block on async code
- Avoid
async void
methods, useasync Task
instead - Learn how to use
Task.WhenAny
andTask.WhenAll
- Read exceptionnotfound.net’s The Ultimate Guide to Asynchronous Programming in C# and ASP.NET
9. New C# features
C# is an evolving language. With every new version, we have more features to write more concise code. These are some of the new features in C# since C# 6.0.
String interpolation
Before we wrote,
string.Format("Hello, {0}", name);
Now we can write,
$"Hello, {name}";
Null-conditional operators
There are two new operators to check for null values: ??
and ?.
.
Before,
string name = ReadNameFromSomewhere();
if (name == null)
name = "none";
else
name.Trim();
After,
string name = ReadNameFromSomewhere();
name?.Trim() ?? "none"
Inlined out variables
Now, we can inline the variable declaration next to the out
keyword.
Before,
int count = 0;
int.TryParse(readFromKey, out count);
After,
int.TryParse(readFromKey, out var count)
Or even,
int.TryParse(readFromKey, out _)
Using declarations
A variable preceded by using
is disposed at the end of the scope.
Before,
using (var reader = new StreamReader(fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// Do something
}
}
After,
using var reader = new StreamReader(fileName);
string line;
while ((line = reader.ReadLine()) != null)
{
// Do something
}
Nullable reference types
All reference variables are non-nullable by default. Any attempt to dereference a nullable reference gets a warning from the compiler. Goodbye, NullReferenceException!
We need to turn on this feature at the project level in our csproj files.
Before,
int notNull = null;
// ^^^^^
// error CS0037: Cannot convert null to 'int'
int? canBeNull = null;
string name = null;
SayHi(name);
// ^^^^^
// System.NullReferenceException
void SayHi(string name) => Console.WriteLine(name.Trim());
After,
string name = null;
// ^^^^^
// warning CS8600: Converting null literal or possible null value to non-nullable type.
string? canBeNullName = null;
SayHi(name);
// ^^^^^
// warning CS8604: Possible null reference argument for parameter 'name'
To learn other techniques to prevent the NullReferenceException, start checking what the NullReferenceException is and when it’s thrown.
Records
A record is an immutable reference type with built-in equality methods. When we create a record, the compiler creates a ToString
method, a value-based equality methods and other methods for us.
public record Movie(string Title, string ReleaseYear);
Top-level statements
All the boilerplate is now gone from Main
methods.
Before,
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
After,
Console.WriteLine("Hello World!");
To learn about other C# features, check my top 10 or so best C# features.
10. Bonus Points
- Learn how to type with all your fingers. At least we will impress people.
- Learn some Vim. Read my post on Learning Vim For Fun and Profit. If you want to master every detail, take a look at the book “Practical Vim”.
- Learn about C# extensions methods. We will find them often.
- Read books on Clean Code. Check my takeaways for The Art of Readable Code and Clean Code.
Voilà! That’s my take on what every intermediate C# developer should know! Don’t be overwhelm by the amount of things to learn. Don’t try to learn everything at once, either. Learn one subject at a time! And, start using it in your every day coding as you learn it.
Happy coding!