CS Programming Fundamentals- A Beginner's Complete Guide
What Is C# and Why Should You Care?
C# (pronounced "C sharp") is a programming language developed by Microsoft. It's been around since 2000 and powers a huge chunk of the software you probably use every day. Visual Studio, Unity games, Windows apps, Netflix's backend — all built with C#.
You should learn it because it pays well and the job market is solid. Full-stack C# developers consistently rank among the better-compensated developers. The language itself is clean, readable, and designed to catch your mistakes before they crash production.
Setting Up Your Environment
You need two things to start: the .NET SDK and a code editor. That's it.
Step 1: Install the .NET SDK
Go to dotnet.microsoft.com/download and grab the latest .NET SDK. The installer takes two minutes. Pick the LTS (Long Term Support) version — it's more stable.
Step 2: Pick Your Editor
- Visual Studio — Full IDE, heavy but powerful. Best for Windows development.
- Visual Studio Code — Lightweight, free, works on every OS. Get the C# extension.
- Rider — JetBrains' C# IDE. Costs money but the debugging tools are worth it.
For beginners, VS Code is the move. Keep it simple.
Step 3: Verify Your Setup
Open your terminal and type:
dotnet --version
If you see a version number, you're good. If not, the SDK didn't install correctly — rerun the installer.
Your First C# Program
Run these commands in your terminal:
dotnet new console -n MyFirstApp
cd MyFirstApp
dotnet run
You just created and ran a program. Open Program.cs in your editor. It looks like this:
Console.WriteLine("Hello, World!");
Change the text inside the quotes. Run dotnet run again. That's your entire development workflow. Congratulations — you just wrote software.
Variables and Data Types
Variables store data. C# is statically typed, which means you declare what type a variable holds before you use it.
Common Data Types
- int — Whole numbers (42, -7, 0)
- double — Decimal numbers (3.14, -0.5)
- string — Text ("Hello")
- bool — True or false
- char — Single character ('A')
Declaring Variables
int age = 25;
string name = "Alex";
double height = 5.9;
bool isEmployed = true;
Notice the syntax: type first, name second, equals sign for assignment, semicolon to end the statement. C# will yell at you if you try to put a string into an int variable. That's a feature, not a bug.
Type Inference
C# can figure out the type when you assign a value immediately:
var score = 100; // Compiler knows this is int
var message = "Game Over"; // Compiler knows this is string
Use var when the type is obvious from the right side of the assignment. Don't use it when you're declaring an empty variable — that's just lazy.
Operators and Expressions
You need to do math and comparisons. Here's what works:
Math Operators
- + Addition
- - Subtraction
- * Multiplication
- / Division
- % Modulus (remainder)
int a = 10;
int b = 3;
int result = a / b; // result is 3, not 3.33 — int division cuts the decimal
Comparison Operators
- == Equal to
- != Not equal to
- > Greater than
- < Less than
- >= Greater than or equal
Comparisons return bool values. 5 > 3 evaluates to true.
Control Flow: Making Decisions
Programs need to branch based on conditions. That's what if/else statements do.
int temperature = 72;
if (temperature > 85)
{
Console.WriteLine("It's hot");
}
else if (temperature > 60)
{
Console.WriteLine("Nice weather");
}
else
{
Console.WriteLine("It's cold");
}
The curly braces {} define a code block. Indentation is optional in C# but you should use it anyway — for humans, not computers.
Switch Statements
When you're checking one variable against multiple values, switch is cleaner:
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
default:
Console.WriteLine("Invalid day");
break;
}
Don't forget the break. Missing it is the most common switch mistake. C# will "fall through" to the next case, which is almost never what you want.
Loops: Repeating Code
You need to run code multiple times. C# gives you several loop types.
for Loop
Use when you know how many iterations you need:
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i); // Prints 0, 1, 2, 3, 4
}
The three parts: initialize (i = 0), condition (i < 5), increment (i++). The loop runs until the condition is false.
foreach Loop
Use when iterating over a collection:
string[] fruits = { "Apple", "Banana", "Cherry" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
This reads as "for each fruit in fruits, print the fruit." Cleaner than a for loop for collections.
while Loop
Use when you don't know the exact iteration count:
int count = 0;
while (count < 3)
{
Console.WriteLine(count);
count++;
}
The condition checks before each iteration. If it's false initially, the loop body never runs.
do-while Loop
Runs at least once, then checks the condition:
int x = 10;
do
{
Console.WriteLine(x);
x--;
} while (x > 0);
Use this when you need the body to execute before the exit condition matters.
Methods: Organizing Your Code
Methods let you reuse code without repeating yourself. They take inputs and optionally return outputs.
int Add(int a, int b)
{
return a + b;
}
int sum = Add(5, 3); // sum is 8
The int before the method name is the return type. If your method doesn't return anything, use void:
void Greet(string name)
{
Console.WriteLine("Hello, " + name);
}
Method Parameters
You can set default values:
void Greet(string name, string greeting = "Hello")
{
Console.WriteLine(greeting + ", " + name);
}
Greet("Sam"); // Prints "Hello, Sam"
Greet("Sam", "What's up"); // Prints "What's up, Sam"
Arrays and Collections
Arrays hold multiple values of the same type. They're fixed-size.
int[] scores = new int[5];
scores[0] = 95;
scores[1] = 82;
// ...
Or initialize with values:
string[] names = { "Alice", "Bob", "Charlie" };
Console.WriteLine(names[1]); // Prints "Bob"
Arrays are zero-indexed. The first element is at index 0, not 1. This trips up every beginner. Get used to it.
Lists: Dynamic Collections
Arrays are fixed-size. Lists grow as you add items:
List tasks = new List();
tasks.Add("Finish report");
tasks.Add("Call mom");
tasks.Add("Buy groceries");
Console.WriteLine(tasks.Count); // Prints 3
tasks.Remove("Call mom");
Console.WriteLine(tasks.Count); // Prints 2
Use List<T> when you don't know how many items you'll have. It's the most common collection type in C#.
Classes and Objects: The Basics
C# is an object-oriented language. Classes are blueprints; objects are instances.
class Dog
{
public string Name;
public string Breed;
public int Age;
public void Bark()
{
Console.WriteLine(Name + " says: Woof!");
}
}
// Creating an object:
Dog myDog = new Dog();
myDog.Name = "Rex";
myDog.Breed = "German Shepherd";
myDog.Age = 3;
myDog.Bark();
Constructors
Set initial values when creating an object:
class Dog
{
public string Name;
public int Age;
public Dog(string name, int age)
{
Name = name;
Age = age;
}
}
Dog myDog = new Dog("Rex", 3);
The constructor has the same name as the class and no return type. It runs automatically when you use new.
Access Modifiers
The public keyword controls who can access your code:
- public — Accessible from anywhere
- private — Accessible only within the same class
- protected — Accessible within the class and subclasses
Default to private. Only expose what needs to be exposed. This prevents bugs and makes debugging less miserable.
Common Errors and How to Fix Them
| Error | Cause | Fix |
|---|---|---|
| CS1002: ; expected | Missing semicolon | Add ; at the end of the line |
| CS0118: 'X' is a 'namespace' but is used like a 'type' | Namespace/class name conflict | Use full namespace or rename |
| CS0161: Not all code paths return a value | Method claims to return but doesn't in all cases | Add return for all paths or change return type to void |
| CS0266: Cannot implicitly convert type X to Y | Type mismatch | Cast explicitly or change variable type |
| CS0120: An object reference is required | Accessing static member via instance | Use class name instead of variable name |
When you see a red squiggle, read the error message first. It tells you exactly what's wrong and which line. Don't panic, don't Google immediately — the compiler usually knows.
Getting Started: A Practical Example
Let's build a simple calculator. Create a new console app:
dotnet new console -n SimpleCalculator
cd SimpleCalculator
Replace Program.cs with:
Console.WriteLine("Simple Calculator");
Console.WriteLine("Enter first number:");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter operator (+, -, *, /):");
string op = Console.ReadLine();
Console.WriteLine("Enter second number:");
double num2 = Convert.ToDouble(Console.ReadLine());
double result = 0;
switch (op)
{
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 != 0)
result = num1 / num2;
else
{
Console.WriteLine("Cannot divide by zero");
return;
}
break;
default:
Console.WriteLine("Invalid operator");
return;
}
Console.WriteLine($"Result: {num1} {op} {num2} = {result}");
Run it with dotnet run. Enter numbers and operators. The program takes input, processes it, and outputs a result. This covers variables, input/output, conditionals, and switch statements — all in one file.
What's Next
You've learned the fundamentals. Here's where to go from here:
- LINQ — Query collections like a database. Transforms how you handle data.
- Exception handling —
try/catchblocks for handling errors gracefully. - File I/O — Reading and writing files on disk.
- Async/await — Writing non-blocking code for better performance.
- Entity Framework — Database access without writing SQL.
Build small projects. A to-do list app. A temperature converter. A basic game. You don't learn programming by reading — you learn by building. The syntax becomes muscle memory after your third or fourth project.