Basic C# Programming Concepts
In this lesson, we’ll cover basic programming concepts using the C# programming language (C-Sharp). The C# programming language is powerful and used in all kinds of applications from web to games to AI and more. As we go, we’ll learn about the difference between JavaScript and C#. Later we will explore the web application framework ASP.NET Core and start building a web application back-end with C#.
It’s recommended to use Visual Studio 2022 to follow along, which you can install for free but you could also use an online C# editor if for some reason you are opposed to installing the IDE.
Create a new Console Application
To start learning basic C# programming concepts, open Visual Studio and select Console App as the projects type. Specify a name a save location for the project, leaving all the default options as they are.
There are many kinds of project templates you can select when you open Visual Studio which make getting started easier. A console app is the simplest form of an application in C#. It has no interface, just the terminal window for interaction and output. When you create a new console app there will be one file called Program.cs with some boilerplate code that writes ‘Hello, World!’ to the console. When you run the application, a console window will appear with ‘Hello, World’ as output.
If you like this course and later become a master C# / ASP.NET developer, check out the Nano ASP.NET Boilerplate. When you obtain the Nano Boilerplate, a new project template will appear as a selection option. You can use this to fast-track development of your new applications. The default project template provided in Visual Studio are very basic. The Nano Boilerplate however will save you hours of work, with all the architecture and essential infrastructure already set up.
Compiled Versus Interpreted Programming Languages
Running the application brings us to the first fundamental difference between JavaScript and C# programming. If you remember with JavaScript, the code would run immediately or whenever we reloaded the browser window.
In C#, the code must be compiled first. What that means is that the code is being translated into machine code before it runs. The compiler checks for errors, optimizes the code, and produces an executable (e.g., .exe
, .dll
). Once compiled, it runs fast and efficiently. There is hardly any code in our console app, so it compiles almost instantly, but the time for a larger application to compile will be noticeable by seconds. Anytime when we click the run button, the code is being compiled.
With an interpreted language like JavaScript, the code is read and executed line-by-line at runtime by an interpreter (like the browser’s JavaScript engine). No pre-compiled binary is created — the interpreter runs your code on the fly. As for performance, it’s typically slower than compiled code, but faster to test and modify.
Variables
Variables are found in every programming language, and in C# its no different. In JavaScript we used let, const, and var for storing values to memory. In C# we can also use the var keyword, but instead of let and const, in C# there are many specific types we can use instead.
This is the next fundamental difference about C# versus other languages like JavaScript. C# is a strong-typed language. This means that it allows you to specify types for every kind of variable and will restrict the usage. Any time there is a type mismatch, it will be highlighted in design-time. Or if compiled, a compile-time error will be thrown, which is good because it allows you to find bugs.
Compile-time refers to the time that you click the play button and the compiler starts compiling code. Design-time refers to the time that you are writing code. Run-time refers to the time that the program is running. It’s always best to find errors before run-time.
To see an example of strong typing in C# let’s take a look at this code:
int age = 30;
string name = "Alice";
// ❌ This will cause a compile-time error:
age = "thirty"; // Cannot assign a string to an int
We have specified that age should only accept an integer (int) type and that name should always be a string. When we try to assign a string value to the age variable, Visual Studio highlights the error for us during design-time. If we try to compile the code, we see the error again and listed in the error list.
You cant mix types unless you convert them explicitly
string ageText = "30";
int parsedAge = int.Parse(ageText); // ✅ Explicit conversion
Comparing with loosely-typed languages like JavaScript, this would be allowed
let age = 30;
age = "thirty"; // ✅ No error — type changes at runtime
This flexibility can be convenient, but also riskier because bugs are more likely to appear at run-time instead of during development (design-time).
Type inference is discouraged but still exists in C# with the var keyword. Using var infers the type — but the variable is still strongly typed.
var message = "Hello"; // message is still a string!
message = 123; // ❌ Compile-time error — can't change type
So var is shorthand, not dynamic typing.
In C#, there are many other types of variables besides integers and strings, a few of the common ones are double (decimal), Boolean, and DateTime.
int age = 30;
string name = "Alice";
double temperature = 75.52353250;
bool active = false;
DateTime date = DateTime.Now;
Console.WriteLine(age);
Console.WriteLine(name);
Console.WriteLine(temperature);
Console.WriteLine(active);
Console.WriteLine(date);
Functions
A function (also called a method in C#) is a reusable block of code that performs a task. It can take input parameters, do some work, and return a result (or not).
A function is declared by specifying the type that will be returned, followed by the name of the function and then parenthesis. If parameters are accepted, they are defined within the parenthesis followed by the code to be executed contained within curly braces.
Here is a function that accepts an age and name parameter and writes a statement to the console window. Since it doesn’t return anything, the type specified is void. The function is called by referencing its name with parenthesis and passing any parameters to it.
int age = 30;
string name = "Alice";
double farenheit = 75.52353250;
bool active = false;
DateTime date = DateTime.Now;
PrintUserInfo(age, name);
void PrintUserInfo(int age, string name)
{
Console.WriteLine(name + " is " + age + " years old");
}
Here is another example function that returns something
double FahrenheitToCelsius(double farenheit)
{
return (f - 32) * 5 / 9;
}
Conditional Logic
In C#, conditional logic works much the same way as JavaScript, using if, else if, and else keywords. Here is an example using all of them:
int score = 75;
if (score >= 90)
{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B");
}
else if (score >= 70)
{
Console.WriteLine("Grade: C");
}
else
{
Console.WriteLine("Grade: F");
}
It’s important to remember that the condition tree execution will end whenever the first condition is met. So if the first condition is true, the second condition will not execute even if it is also true.
You can also use the shorthand ternary conditional like this:
void PrintUserInfo(int age)
{
string status = (age >= 18) ? "Adult" : "Minor";
Console.WriteLine(status);
}
Classes, Objects and Methods
Classes, objects and methods are core concepts in C# and the foundation of object-oriented programming (OOP). A class is a real-world entity represented in code and objects are instances of a class. On other words, the class is like a blueprint and the object is the actual thing. Classes are defined using the class keyword followed by their name, for example:
class Person
{
public string Name;
public int Age;
public void Greet()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}
In this code, the Person is a class, Name and Age are fields (variables inside the object) and Greet() Is a method (function inside the object). To create an instance of a class (an object) use the new keyword. Here is an example of how we can use the person class to create an object, populate its fields and use its method.
Person p1 = new Person(); // Create object
p1.Name = "Alice"; // Set fields
p1.Age = 30;
p1.Greet(); // Call method
A method is a function which belongs to a class (or object). It can access or change the object’s data, perform operations and return a value. In the previous example we called the Greet method on the person object which output the message to the console window.
Arrays
An array is a collection of variables of the same type, stored in a single container. The difference from JavaScript is that with C#, the type is enforced. To declare an array, use brackets. Here is an example of an array of integers.
int[] numbers = { 10, 20, 30, 40 };
Arrays use zero-based indexing, the first element is at index zero. Here is how you can access individual items of an array:
Console.WriteLine(numbers[1]); // Output: 20
It’s actually not that common to work with arrays in C# because they are quite restrictive. For one, they cannot be resized. You cannot add or remove items in an array. Instead its more common to use a List.
Lists are better because they are way more flexible. For starters, they contain methods that can add or remove items easily. The List type must be imported from Systems.Collections.Generic. Here is an example of using a list:
List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");
names.Add("Charlie");
foreach (string name in names)
{
Console.WriteLine(name);
}
The reason that we must import the List type is that it’s not a primitive type built into C#. It’s very common though
Loops
In C#, loops work exactly as they do in JavaScript. A loop is a programming structure that repeats a block of code as long as a condition is true or for each item in a collection. There are four common ones in C#: for, foreach, while, do while.
A while loop checks a condition before each iteration and executes the code while the condition is true. For example:
int counter = 0;
while (counter < 3)
{
Console.WriteLine("Repeating...");
counter++;
}
A foreach loop is best for arrays and lists. This kind of loop goes through each item in a collection.
string[] colors = { "Red", "Green", "Blue" };
foreach (string color in colors)
{
Console.WriteLine(color);
}
If an end condition is never met, an infinite loop will occur, resulting in a run-time error. For any kind of loop you can use the break keyword to stop it entirely.
You can also use the continue keyword to skip to the current iteration. For example
for (int i = 1; i <= 9; i++)
{
if (i == 3) continue; // skip 3
if (i == 5) break; // stop at 5
Console.WriteLine(i);
}
Conclusion
You will find the same programming fundamentals across all languages including backend development with C#. C# is a strongly-typed language, meaning that variable types can be declared and enforced, making it easier to catch bugs in design-time. It’s also an Object-Oriented Programming (OOP) language, which means it’s a programming style that organizes code into objects, which are based on classes. C# is compiled language, which means that it’s translated from what you write into machine code.
C# makes for an excellent back-end solution when used with the web application framework ASP.NET. The primary functions of web applications are to take requests via API and moving things around in databases. Before we begin building a web application, we will learn about database function and design in the next lesson.