No history yet

C# Basics

Getting Started with C#

C# is the language you'll use to build powerful web applications with ASP.NET. It’s a modern, versatile language developed by Microsoft. Before you can write any code, you need a place to write and run it. This is where an Integrated Development Environment, or IDE, comes in.

The most common IDE for C# development is Visual Studio. It includes a code editor, a debugger to help find errors, and tools to run your application, all in one place.

To get started, you'll need to install Visual Studio Community, which is free. During installation, you'll be prompted to choose workloads. Make sure to select the "ASP.NET and web development" workload, as this will install all the necessary tools for building web apps with C#.

Lesson image

Your First C# Program

The best way to learn is by doing. Let's create a simple "Hello, World!" program. This is a tradition in programming that displays the message "Hello, World!" on the screen. It's a great first step to confirm your environment is set up correctly and to see the basic structure of a C# program.

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            // This line prints "Hello, World!" to the console.
            Console.WriteLine("Hello, World!");
        }
    }
}

Let's break that down line by line.

  • using System; tells our program that we want to use features from the System library, which contains fundamental tools, including the Console we use for output.
  • namespace HelloWorld creates a container to organize our code. As projects grow, namespaces prevent naming conflicts.
  • class Program is a container for our methods and variables. In C#, all code lives inside a class.
  • static void Main(string[] args) is the entry point of our application. When you run the program, the Main method is the first thing that gets executed.
  • Console.WriteLine("Hello, World!"); is the line that does the work. It calls the WriteLine method to print the text "Hello, World!" to the console.

Notice the curly braces {} and semicolons ;. The braces define the beginning and end of code blocks, like the namespace or class. The semicolon marks the end of a statement, much like a period in a sentence.

Storing and Using Data

Programs need to work with information, like user names, ages, or prices. We store this information in variables. A variable is just a named storage location in memory. Each variable must have a specific data type, which tells the computer what kind of data it can hold.

Data TypeDescriptionExample
intStores whole numbers (integers).int userAge = 25;
doubleStores numbers with decimal points.double price = 19.99;
stringStores sequences of text.string userName = "Alex";
boolStores a true or false value.bool isLoggedIn = true;

Declaring a variable involves giving it a type and a name. You can also assign it a value at the same time.

// Declaring an integer variable
int score;

// Assigning a value to it
score = 100;

// Declaring and assigning in one line
string playerName = "Maria";

Console.WriteLine(playerName);
Console.WriteLine(score);

Once you have variables, you can perform operations on them using operators. Common operators include + (addition), - (subtraction), * (multiplication), and / (division). The = operator is used for assignment, giving a variable its value.

int a = 10;
int b = 5;
int sum = a + b; // sum is now 15

double wallet = 50.0;
double itemCost = 12.50;
double remaining = wallet - itemCost; // remaining is now 37.5

Controlling Program Flow

Your programs won't always run the same way from top to bottom. Sometimes you need to make decisions or repeat actions. This is called control flow.

The if statement allows you to run code only if a certain condition is true.

int playerHealth = 75;

if (playerHealth > 50)
{
    Console.WriteLine("Player is in good shape.");
}
else
{
    Console.WriteLine("Player needs a health pack!");
}

Loops are used to repeat a block of code multiple times. A for loop is great when you know exactly how many times you want to repeat an action.

// This loop will run 5 times, printing numbers 0 through 4.
for (int i = 0; i < 5; i++)
{
    Console.WriteLine("Current count: " + i);
}

A while loop continues to run as long as its condition remains true. This is useful when you don't know in advance how many repetitions are needed.

int ammo = 6;

while (ammo > 0)
{
    Console.WriteLine("Firing! Ammo left: " + ammo);
    ammo = ammo - 1; // Decrease ammo by 1
}

Interacting with the User

A program is more interesting when it can interact with a user. You've already seen Console.WriteLine() to display information. To get input from the user, you can use Console.ReadLine().

Console.ReadLine() reads a line of text that the user types into the console and returns it as a string.

Console.WriteLine("What is your name?");

// Read the user's input and store it in the 'name' variable
string name = Console.ReadLine();

// Greet the user by name
Console.WriteLine("Hello, " + name + "!");

Keep in mind that Console.ReadLine() always gives you a string. If you need a number, you'll have to convert it. For example, Convert.ToInt32(someString) can turn a string into an integer.

Now's a good time to check your understanding of these fundamental concepts.

Quiz Questions 1/6

When installing Visual Studio to build web applications with C#, which workload is essential to select?

Quiz Questions 2/6

What is the name of the method that serves as the starting point for a C# console application?

These are the building blocks of C#. With variables, operators, and control structures, you can start writing simple but powerful programs.