Getting Started
Types and Variables
Learn C# value types, reference types, nullable types, and type inference.
Value Types vs Reference Types
Value types store data directly:
- Primitives:
int,double,bool,char,decimal - Structs
- Enums
Reference types store a reference to data:
string,object, arrays- Classes, interfaces, delegates
Nullable Types
By default, value types can't be null. Add ? to make them nullable.
With C# 8+ nullable reference types enabled, you can prevent null reference exceptions more effectively.
Type Inference
Use var to let the compiler infer the type. The type is still static — var is not dynamic.
Example
csharp
using System;
// Value types
int age = 30;
double pi = 3.14159;
decimal money = 1234.56m; // m suffix for decimal
bool isAdmin = false;
char initial = 'A';
// Reference types
string name = "Alice";
object obj = new object();
int[] numbers = { 1, 2, 3, 4, 5 };
// Nullable value types
int? maybeNull = null;
int? withValue = 42;
Console.WriteLine(maybeNull ?? -1); // -1 (null coalescing)
Console.WriteLine(withValue ?? -1); // 42
// Null-conditional operator
string? nullableStr = null;
Console.WriteLine(nullableStr?.Length); // null (no exception)
Console.WriteLine(nullableStr?.ToUpper() ?? "default");
// var - type inference
var count = 10; // int
var message = "Hello"; // string
var list = new List<int>(); // List<int>
// Constants
const double PI = 3.14159;
const string API_KEY = "my-key";
// Enums
enum DayOfWeek { Monday, Tuesday, Wednesday, Thursday, Friday }
DayOfWeek today = DayOfWeek.Wednesday;
Console.WriteLine(today); // Wednesday
Console.WriteLine((int)today); // 2
// is and as operators
object someObj = "Hello";
if (someObj is string str) {
Console.WriteLine(str.Length);
}
// Pattern matching
object num = 42;
var description = num switch {
int n when n < 0 => "negative",
0 => "zero",
int n when n > 0 => "positive",
_ => "not a number"
};Try it yourself — CSHARP