Variables and Constants in C#
Declare variables with explicit types and var, define constants with const and readonly, and understand scope and naming conventions.
Introduction to Variables
1. What is a Variable?
A variable is a named storage location in memory. In C#, every variable has a fixed type declared at compile time.
Declaring Variables
1. Explicit Type Declaration
Declare a variable by writing the type followed by the name. You can declare without assigning — but you must assign before using.
2. var (Type Inference)
`var` lets the compiler infer the type from the assigned value. The type is still fixed at compile time — `var` is not dynamic.
3. Multiple Variable Declaration
Declare multiple variables of the same type in one line, or declare them separately.
Constants
1. const
`const` declares a compile-time constant. Its value must be known at compile time and can never be changed.
2. readonly
`readonly` can be set once — either at declaration or in a constructor. Unlike `const`, its value can come from runtime expressions.
3. const vs readonly
A side-by-side comparison of when to use `const` vs `readonly`.
Naming Rules & Scope
1. Naming Conventions
C# has well-established naming conventions enforced by the community and tools like Roslyn analyzers.
2. Block Scope
Variables in C# are block-scoped — they only exist within the `{}` block they are declared in.
3. Reassignment
Variables declared with a type or `var` can be reassigned. `const` and `readonly` cannot.
Best Practices
1. Recommended Guidelines
Follow these conventions for clean, idiomatic C# variable usage.