Appearance
Variables & Data Types
Variables are containers for storing data values. C# is a strongly-typed language, which means every variable must have a declared type. Understanding variables and data types is fundamental to C# programming.
Variable Declaration
Variables must be declared before they can be used. C# supports type inference using the var
keyword, allowing the compiler to determine the type based on the assigned value.
csharp
// Type inference
var name = "John"; // Compiler infers string type
var age = 25; // Compiler infers int type
// Explicit typing
string firstName = "John";
int userAge = 25;
bool isActive = true;
Common Data Types
Value Types
Value types directly contain their data and are stored on the stack. Each variable has its own copy of the data.
csharp
int number = 42; // Whole numbers
float price = 19.99f; // Single-precision floating point
double amount = 99.99d; // Double-precision floating point
decimal precise = 123.456m; // High-precision decimal
bool isValid = true; // Boolean true/false
char grade = 'A'; // Single character
Reference Types
Reference types store a reference to their data, which is stored on the heap. Multiple variables can reference the same data.
csharp
string name = "John Doe"; // String of characters
object obj = new object(); // Base type of all objects
dynamic dynamicVar = 100; // Type checking at runtime
Constants
Constants are immutable values that cannot be modified after declaration. They must be initialized at declaration time.
csharp
const double PI = 3.14159;
const string APP_NAME = "MyApp";
const int MAX_USERS = 100;