C#

C# Fundamentals

19 lessons

Progress0%
1. Introduction to C#
1What is C#?
2. Variables and Data Types
1Data Types in C#
3. Control Flow
ConditionalsLoops
4. Methods
Defining MethodsOptional Parameters and Overloading
5. Object-Oriented Programming
Classes and PropertiesInheritanceInterfaces and Generics
6. LINQ and Async
LINQ Queriesasync/await
7. Exception Handling
try/catch/finally & Exception TypesCustom Exceptions & IDisposable
8. Delegates & Events
Delegates & LambdaEvents & Event Handlers
9. Records & Pattern Matching
Record TypesPattern Matching & Switch Expressions
10. File I/O & JSON
File & Stream OperationsJSON Serialization
All Tutorials
C#Variables and Data Types
Lesson 2 of 19 min
Chapter 2 · Lesson 1

Data Types in C#

C# is a strongly typed language with value types and reference types.

Value Types (stored on stack):

  • Numeric: int, long, float, double, decimal
  • Boolean: bool
  • Character: char
  • Struct and enum

Reference Types (stored on heap):

  • string
  • object
  • class instances
  • arrays

var Keyword: Type inference - compiler figures out the type.

Nullable Types: Value types can be made nullable with ?. C# 8+ has nullable reference types.

const vs readonly:

  • const: Compile-time constant
  • readonly: Runtime constant (can be set in constructor)

Code Examples

C# Data Typescsharp
// Value types
int number = 42;
long bigNumber = 9999999999L;
float singlePrecision = 3.14f;
double doublePrecision = 3.14159265359;
decimal money = 19.99m;  // For financial calculations
bool isActive = true;
char letter = 'A';

Console.WriteLine($"int: {number}");
Console.WriteLine($"decimal: {money}");

// Type inference with var
var inferredString = "Hello";  // string
var inferredInt = 42;          // int
var inferredList = new List<string>();  // List<string>

// Nullable value types
int? nullableInt = null;
nullableInt = 42;

if (nullableInt.HasValue)
{
    Console.WriteLine($"Value: {nullableInt.Value}");
}

// Null coalescing
int result = nullableInt ?? 0;  // Use 0 if null

// String types
string greeting = "Hello";
string multiLine = """
    This is a
    multi-line string
    """;

// Constants
const double PI = 3.14159;
// PI = 3.14;  // Error! Cannot modify const

// Implicit vs explicit casting
int intVal = 100;
double doubleVal = intVal;     // Implicit (safe)
int backToInt = (int)doubleVal; // Explicit (may lose data)

Console.WriteLine($"Converted: {backToInt}");

C# has distinct value and reference types. Use decimal for financial calculations to avoid floating-point errors.

Quick Quiz

1. Which type should you use for financial calculations in C#?

Was this lesson helpful?

PreviousNext