I’ve been making it my mission more recently to try and reduce the barriers for people that want to get started with programming. If you’re just getting started out, it can be incredibly intimidating and often leaves folks quitting before they get started. When you factor in just how many programming languages there are to pick from, it’s yet another barrier for getting started. How do you pick? What’s the best one? I’ve spoken before about how to approach getting started and if you’re open to starting with the “dotnet” ecosystem then this C# basics article is for you!
(Read the original article on C# basics here)
For some history, C# was originally created back in 2000 although if you check out this other page, we can see that it looks like C# 1.0 was actually out in 2002. For homework, you can go read about all of the C# vs Java debate!
When we think about C# basics, we’ll be looking at actual C# code but nearly every concept we touch on is applicable to other languages as well. So please keep in mind that as you’re reading through, there are going to be many things you can apply to other languages later if you’d like to try something else out. None of this is a waste of time should you like to learn an additional language!
In this article, we’ll go over the C# basics, from setting up your environment to write code effectively to !
If you just wanted to try writing out some code to cover the C# basics, you could use an online compiler like .NET Fiddle. I’d argue that using an online compiler like this is one of the quickest low-barrier ways just to jump into writing code. However, this will come with limitations, so if you’re trying to pursue building some applications you’ll want to take the next step.
This will mean that you’ll need to set up your local development environment, and this involves installing a code editor or integrated development environment (IDE) that supports writing and compiling C# code. IDE’s will even let you step through and debug your code so you can investigate what your code is doing. Some of the most popular options include:
Once your IDE is installed, we can get right into everyone’s first program… “Hello, World!”. We’ll walk through what’s happening in the following code, which you can copy and paste right into a new project that you create!
using System;
namespace MyFirstProgram
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
In the code above, the using
keyword tells the compiler that we would like to access functionality defined in a particular namespace
. The analogy that I like to use here is that a namespace
is like a folder structure, and when we are asking the compiler to use things from a namespace
it’s like having access to that folder. Of course, this is an analogy, but I think about it this way from a code organization perspective. The System
namespace
provides many fundamental things that we’ll be accessing in most of our C# programs.
After this, we actually define our very own namespace
called “MyFirstProgram”. As you can see, we have some curly braces after that and code that gets nested inside of those curly braces. So this will mean that all of the code we put inside will belong to the namespace
“MyFirstProgram”.
We define a new class
called “Program” inside of the namespace, where a class
is used to group functionality into a particular type
. The file-folder analogy I started with begins to break down a little bit more here, but you can think about a class
almost like a file in one of your folders (i.e. your namespace
). In this particular code example, the “Program” class
is the entry point to the program we are writing, so when your program starts up it will look for the static
method
called “Main” on your “Program” class
. The string[] args
portion that you see is a parameter (in this case, an array of command-line arguments) that can be passed to our program.
Finally, inside the Main method, we use the Console.WriteLine
method to write the text “Hello, World!” to the console. So if you think about a command prompt window, this program just outputs those words for you to see. And that’s it!
Admittedly, for your very first program, that structure doesn’t seem too friendly. Why the heck did we need to write so many things down and have to explain so many concepts just to be able to see some text get printed out?!
You’re right. And in fact, in newer versions of the language this was addressed with top-level statements. You can take advantage of this with C# 10 and beyond. Top-level statements get rid of all of the extra bloat so you can literally just make your Hello World program look like this:
Console.WriteLine("Hello, World!");
That’s WAY more friendly, right? I started with the legacy example for a couple of reasons:
When we’re creating programs, we often need something that can hold different values for us. We need some state in our algorithms or things to hold counts etc… These are referred to as “variables”. C# has some requirements for variables, including having to define them and assign a “type” to them. Here’s an example:
int myNumber = 1337;
This example code shows an integer (int
as the first word written there) that we are declaring with the name “myNumber”. We also assign the value of 1337 to that integer. So this shows a declaration of a variable AND an assignment put together. You could separate these onto multiple lines if you wanted:
int myNumber;
myNumber = 1337;
C# is referred to as a “strongly typed” language, which means that all of our variables have to be declared with a specific type. There are more advanced topics related to this where that rule is broken, but we’re not there quite yet! C# has many different types available to us for use right away, and these include some primitive types such as:
Here’s an example of using variables and data types in a program:
using System;
namespace VariablesAndDataTypes
{
class Program
{
static void Main(string[] args)
{
int myNumber = 1337;
float myFloat = 133.7;
double myDouble = 133.7;
bool myBool = true;
string myString = "Hello, World!";
}
}
}
“if statements” are a type of control flow that allows you to execute specified code if a condition is met. That is, if you have code that conditionally should be executed, you can put it inside of an “if statement”. “if statements” are one of the key elements of C# basics, but they also apply nearly universally to other programming languages as the basic building block for branching logic.
Here’s an example of an “if statement” that contains else
branches as well that will determine if a number is positive, negative, or zero:
int num = 5;
if (num < 0)
{
Console.WriteLine("The number is negative.");
}
else if (num > 0)
{
Console.WriteLine("The number is positive.");
}
else
{
Console.WriteLine("The number is zero.");
}
We can also use what is called a switch statement to do this, and in this example we’ll use a feature called pattern matching:
int num = 5
string result = num switch
{
> 0 => "The number is positive.",
< 0 => "The number is negative.",
_ => "The number is zero.",
};
Console.WriteLine(result);
Another foundational piece of our C# basics, and really any programming language, is the concept of loops. Loops allow us to execute code multiple times with potentially varying states until some conditions are met.
In C#, we have the following types of loops available to us:
for
loops: Used to execute a code block a specific number of times.while
loops: Used to execute a code block repeatedly, as long as a given condition is true.do-while
loops: Used to execute a code block repeatedly, until a given condition is no longer true.foreach
loops: Used to iterate over the elements of a collection or array.
Let’s have a look at some example code that uses a for
loop to iterate through an array (i.e. a collection) of integers:
int[] numbers = { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
In the code above, our for
loop starts at 0 using an integer variable called i
that will increment by 1 each iteration of the loop but only while the value of i
is less than the length of the array. And if you’re wondering why we start at zero and only while it’s less than the length of the array, that’s because the first position in an array is actually index 0! It takes some getting used to, but many programming languages are zero-based like this, so position 1 is actually index 0.
We could write similar code using a foreach
loop:
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers){
Console.WriteLine(num);
}
Here you’ll notice that we don’t need to index into a position in the array. Instead, we walk through it one number at a time!
In programming, methods and functions refer to code that we can label with an identifier and reuse throughout a program. In C#, we define methods and functions within a class
(or if you’re using those fancy top-level statements then they can exist outside of a class
) and they are composed of:
private
, so only within the current class
).void
if there is no return type.
Here’s an example of a simple method:
int AddNumbers(int num1, int num2)
{
return num1 + num2;
}
In the above example, because there is no access modifier at the start of the method signature, it will be private
. This method will return an integer, is named “AddNumbers”, and takes two integer parameters (num1
and num2
). When we look at the actual body of the method, we can see that it is adding the two numbers together, and then we have the return
keyword that says we’ll be providing the sum of those two numbers to the caller of this method as the result.
We’ve already seen a couple of examples of these, but a class
is the fundamental building block of object-oriented programming in C#. I used the analogy of a file in a file system earlier when referring to how we’d organize them within namespaces
, but a class defines the properties and methods of a certain type of object.
When we have defined the functionality of a class
, we can create a new instance of that class to be used using the new
keyword. This allocates into memory a new reference of the class
for us to work with. The exception here is when we deal with the static
keyword, but that’s homework!
Before we jump into this example, I briefly mentioned “properties” and it’s worth mentioning that a property in C# is very much like the methods we already looked at. However, in the most simple case, a property is a special method that allows us to get and/or set a value on a class. Under the hood, these are just methods like we saw earlier, but we get some fancy syntax to make these stand out.
Here’s an example of a simple class with two properties and a method that will print some information:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public void PrintInfo()
{
Console.WriteLine("Mm name is " + Name + " and I am " + Age + " years old.");
}
}
That means if we made more than one instance of the class, we could have two different Person
references with different values:
Person p1 = new Person();
p1.Name = "Nick"
p1.Age = 33;
Person p2 = new Person();
p2.Name = "Jamal";
p2.Age = 18;
p1.PrintInfo();
p2.PrintInfo();
Running the code above would print out information for two different Person
objects!
C# shares many similar building blocks that we see in other programming languages, especially object oriented programming languages. We looked at the basic structure of a C# program and things like storing information in variables, controlling the flow of code, and a simple example of objects.
C# is a powerful language though, and while we were focused on the C# basics, there’s a lot more that we can do! Developers build games, websites, scalable distributed services, mobile apps, etc… all with C#!
C# is my favorite language, and I hope that as you read through you found it interesting to see the basics of it. I’d encourage you to check out this playlist if you’re interested in beginner programming topics, and alternatively if you’d just like to see more programming material then this playlist would suit you!
Read the original article on C# basics here.