C# Tutorial

Variables & Types

Value types vs Reference types, var, and nullable types

Strong Statically Typed

In C#, every variable must have a type. The compiler uses this to ensure that you are using your data correctly and to optimize the generated code.
csharp
int count = 42;
string name = "Alpha";
bool isReady = true;

Value Types vs. Reference Types

Wait! This is the most important architectural concept in C#.
  1. Value Types: Stored on the Stack. They contain the actual data. (e.g., int, double, bool, struct).
  2. Reference Types: Stored on the Heap. The variable contains a reference (address) to the actual data. (e.g., string, class, interface).

Implicit Typing (var)

You can use the var keyword to let the compiler infer the type for you. This is highly recommended for readability, especially with complex types.
csharp
var users = new List<string>(); // Compiler knows this is a List<string>
Wait! var is still strongly typed. Once the type is inferred, it cannot be changed.

Nullable Types

By default, value types (like int) cannot be null. If you need them to be optional, you add a ? to the type name.
csharp
int? age = null; // Valid!
Modern C# also introduced Nullable Reference Types, which help prevent the "billion-dollar mistake" of null pointer exceptions.

Common Data Types

CategoryTypesDescription
Integersint, long, short, byteint is 32-bit (Default)
Floatingdouble, float, decimaldecimal is best for money!
Textstring, charstring is immutable
Booleanbooltrue or false
ObjectobjectThe base type for everything

Summary

TermDescription
varImplicitly typed local variable
StackFast, temporary memory for value types
HeapDynamic memory for reference types
constImmutable value evaluated at compile-time
readonlyImmutable value evaluated at runtime
NullableTypes that can hold null (e.g., int?)
CastExplicitly converting types ((int)myDouble)
LogicStrong types catch errors before you even run the code
SafetyType safety prevents accidental data corruption
Modernnint and nuint for platform-specific integers
PrecisionUse decimal for financial calculations!
StandardUse PascalCase for properties and camelCase for variables