Variables & Types
Declaring and using variables
Introduction
In this lesson, you'll learn about variables & types in C#. Coming from C, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In C, you're familiar with declaring and using variables.
C# has its own approach to declaring and using variables, which we'll explore step by step.
The C# Way
Let's see how C# handles this concept. Here's a typical example:
using System;
int age = 30;
float score = 9.5f;
double pi = 3.14159;
char letter = 'A';
const int Max = 100;
bool active = true; // real bool type
// var — type inference
var name = "Alice"; // inferred as string
Console.WriteLine(string.Format("age={0}, pi={1:F2}", age, pi));Comparing to C
Here's how you might have written similar code in C:
#include <stdio.h>
int main() {
int age = 30;
float score = 9.5f;
double pi = 3.14159;
char letter = 'A';
const int MAX = 100;
int active = 1; /* no bool */
printf("age=%d, pi=%.2f\n", age, pi);
return 0;
}You may be used to different syntax or behavior.
C# has a real bool type (true/false); C uses int
You may be used to different syntax or behavior.
C# var keyword infers types like C's auto; C requires explicit types
You may be used to different syntax or behavior.
C# const is compile-time; C's const is merely read-only
You may be used to different syntax or behavior.
C# has nullable types (int?) for optional values
Step-by-Step Breakdown
1. Boolean Type
C# has a dedicated bool type with true/false literals. C uses int (0 for false, non-zero for true).
int active = 1;bool active = true;2. Type Inference
C#'s var keyword infers the type from the right-hand side, similar to C's __auto_type or C++'s auto.
var name = "Alice"; // string
var count = 42; // int
var items = new List<string>();3. Nullable Types
C# nullable value types (int?) can represent the absence of a value — replacing the C pattern of using -1 or a sentinel value.
int? maybeAge = null;
if (maybeAge.HasValue)
Console.WriteLine(maybeAge.Value);Common Mistakes
When coming from C, developers often make these mistakes:
- C# has a real bool type (true/false); C uses int
- C# var keyword infers types like C's auto; C requires explicit types
- C# const is compile-time; C's const is merely read-only
Key Takeaways
- C# bool (true/false) replaces C int 0/1
- var infers types like C++ auto
- C# const is compile-time constant
- Nullable types (int?) represent missing values