Zero to Hero: Journey of Mastering C# From Scratch
In this blog post, we’ll explore the basic syntax of the C# language. To get started with C#, you need to download .NET from Microsoft. Once downloaded and installed on your computer, run the following command in the terminal to check if it’s installed properly:
dotnet - version
To create a new C# project, run the below command in your terminal within the folder where you wish to create the project:
dotnet new console
Below is a sample code snippet. To run this (assuming you’re using VS Code), save the code and type dotnet run
in the terminal.
Here’s an example of variable declaration:
{
static void Main(string[] args)
{
// Initialize basic value type variables
int num = 20;
float flt = 3.5f;
decimal dec = 5.5m;
bool isTrue = false;
char letter = 'd';
// Initialize a string variable, essentially a sequence of characters
string text = "example text";
// Use implicit typing for variables, not recomanded use unless required
var implicitInt = 15;
var implicitString = "Greetings!";
// Initialize arrays of specific types
int[] numbers = new int[4];
string[] words = { "alpha", "beta", "gamma" };
// Display the variables utilizing string formatting
Console.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}", num, letter, isTrue, text, flt, dec, implicitInt, implicitString);
// A "null" value signifies the absence of a value
object nullableObject = null;
Console.WriteLine(nullableObject);
// Automatic type conversion between compatible types
long largeNumber;
largeNumber = num;
// Cast variables explicitly when necessary
float numToFloat = (float)num;
Console.WriteLine("{0}", numToFloat);
int floatToInt = (int)flt;
Console.WriteLine("{0}", floatToInt);
}
}
Example of operations in C#:
{
// Initialize variables to demonstrate operator usage
int num1 = 8, num2 = 4;
string firstString = "Hello", secondString = "World";
// Demonstrate basic arithmetic operators: +, -, *, /
Console.WriteLine("----- Arithmetic Operations -----");
Console.WriteLine((num1 - num2) + num1); // Subtraction followed by addition
Console.WriteLine(firstString + " " + secondString); // String concatenation
// Show how increment/decrement operators work
Console.WriteLine("----- Increment/Decrement -----");
num1++;
num2--;
Console.WriteLine(num1); // num1 is now 9
Console.WriteLine(num2); // num2 is now 3
// Illustrate shorthand assignment operators
firstString += " " + secondString; // Same as firstString = firstString + " " + secondString;
Console.WriteLine(firstString); // Outputs concatenated string
// Using logical operators: && (AND), || (OR)
Console.WriteLine("----- Logical Operators -----");
Console.WriteLine(num1 < num2 && num2 < 5); // False: logical AND ,num1 is not less than num2
Console.WriteLine(num1 < num2 || num2 < 5); // True: logical OR ,num2 is less than 5
// Demonstrating null-coalescing operators
string sampleText = null;
// The ?? operator returns the left-hand operand if it's not null, otherwise the right-hand operand
Console.WriteLine(sampleText ?? "Sample Text Unavailable");
// The ??= operator assigns the right-hand operand to the left-hand operand if the left-hand operand is null
sampleText ??= "Assigned Text";
Console.WriteLine(sampleText); // Outputs "Assigned Text"
}
The use of ??
and ??=
was a bit new to me when I was new to C#, but it's widely used in C# programming to avoid null pointer exceptions.
Next, let’s talk about commenting your code. As you can see in the earlier codes, you can use //
for single-line comments and /* */
for multi-line comments. You can also use ///
for XML comments for documentation. However, I won’t discuss this further in this post.
Now, let’s move on to writing if and switch statements:
{
static void Main(string[] args)
{
int myNumber = 45;
// Decision making with if-else
if (myNumber == 45) {
Console.WriteLine("myNumber equals 45");
}
else if (myNumber > 45 && myNumber <= 55) {
Console.WriteLine("myNumber is in the range of 46 to 55");
}
else {
Console.WriteLine("myNumber falls outside the expected range");
}
// -----------------------
// Demonstrating the ternary operator ?:
// An example of a two-case decision made with if-then
if (myNumber < 45) {
Console.WriteLine("myNumber is considered lower");
}
else {
Console.WriteLine("myNumber is considered higher");
}
// The same decision above can be simplified using a ternary operator ?:
Console.WriteLine(myNumber < 45 ? "myNumber is considered lower" : "myNumber is considered higher");
}
}
{
static void Main(string[] args)
{
int myNumber = 45;
// Demonstrating the switch statement
switch (myNumber) {
case 45:
Console.WriteLine("The number is exactly 45");
break;
case 46:
Console.WriteLine("The number is 46");
break;
// Grouping cases for a range effect
case 47:
case 48:
case 49:
Console.WriteLine("The number is between 47 and 49");
break;
default:
Console.WriteLine("The number is outside the range of interest");
break;
}
}
}
Remember to include a break
statement after each case in a switch statement to prevent fall-through to subsequent cases, and it’s advised to always include a default
case. We will discuss more about switch expressions in part 2 of this blog.
Now, let’s dive into loops, which will give you an idea about for
and foreach
loops:
static void Main(string[] args)
{
int targetNum = 10;
int[] sampleNumbers = new int[] {2, 4, 6, 8, 10};
string sampleText = "How much wood would a woodchuck chuck if a woodchuck could chuck wood";
// Demonstrating the basic for loop
Console.WriteLine("Demonstrating the basic for loop:");
for (int index = 0; index < targetNum; index++) {
Console.WriteLine("Current index is {0}", index);
}
Console.WriteLine();
// Demonstrating the foreach loop for iterating over sequences
Console.WriteLine("Demonstrating the foreach loop:");
foreach (int num in sampleNumbers) {
Console.WriteLine("Current number is {0}", num);
}
// Counting the number of 'w's in the string
var count = 0;
foreach (char letter in sampleText) {
if (letter == 'w') {
count++;
}
}
Console.WriteLine("Found {0} 'w' characters", count);
}
Let’s move on to while loops, to understand the difference between while
and do-while
loops:
static void Main(string[] args)
{
string userInput = "start"; // Set an initial value that doesn't match the exit condition
// Basic while loop checks condition before execution
Console.WriteLine("Demonstrating the basic while() loop:");
while (userInput != "stop") {
Console.WriteLine("Type 'stop' to exit the while loop.");
userInput = Console.ReadLine();
Console.WriteLine("You entered: {0}", userInput);
}
Console.WriteLine();
// Reset userInput for the do-while example
userInput = ""; // Ensures the do-while loop executes exactly once
// The do-while loop will execute at least once regardless of the initial condition
Console.WriteLine("Demonstrating the do-while() loop:");
do {
if (!string.IsNullOrEmpty(userInput)) {
Console.WriteLine("Type 'exit' to exit the do-while loop.");
}
userInput = Console.ReadLine();
Console.WriteLine("You entered: {0}", userInput);
} while (userInput != "exit");
Console.WriteLine();
}
While loops and do-while loops may seem similar, they are not. A do-while loop will run at least once, no matter the condition, but this is not the case with a while loop.
Now, as we have a basic idea of if conditions, switch statements, and loops, let’s explore the application of break
and continue
:
static void Main(string[] args)
{
int[] numbers = {10, 22, 8, 14, 18, 25, 33, 5, 45};
Console.WriteLine("Demonstrating break and continue:");
foreach (int num in numbers)
{
// If the number is between 15 and 24, skip to the next iteration
if (num >= 15 && num <= 24) {
continue; // Skips printing and moves to the next number
}
// Display the current number
Console.WriteLine($"Current number: {num}");
// Exit the loop if the number is 35 or greater
if (num >= 35) {
break; // Stops the loop
}
}
}
When you use break
, it will break from the loop and exit it. When you use continue
, the flow will skip the rest of the code in the current iteration and move to the next iteration.
I hope you’ve gained a basic understanding of C# syntax through this discussion. In part 2, we will learn more about string formatting and interpolations, basic exception handling, C# functions (and other object-oriented principles), and enums.
Please let me know your thoughts in the comments.