Variables & Constants
var, let-like patterns, naming, and const/readonly.
Variables and Constants in C#
Variables and constants are fundamental building blocks of C# programming. Whether you are creating a console application, developing an ASP.NET Core Web API, or building an enterprise application, you need variables to store information and constants to represent values that should not change.
In C#, understanding how to declare variables, use the var keyword, follow naming conventions, and choose between const and readonly helps you write cleaner, safer, and more maintainable code.
This guide explains each concept with practical C# examples, making it suitable for beginners preparing for real-world development and .NET interviews.
1. What Is a Variable in C#?
A variable is a named storage location that allows a program to hold and work with a value. Depending on its type, a variable can store information such as a name, age, price, or whether a user is active.
For example, consider an application that displays a user's details. You can use variables to store the user's name and age.
string name = "Shreya";
int age = 24;
Console.WriteLine(name);
Console.WriteLine(age);
Output:
Shreya
24
In this example, name is a variable of type string, which stores text, while age is an int variable that stores a whole number.
How to Declare a Variable
A variable declaration generally follows this structure:
dataType variableName = value;
For example:
int employeeId = 101;
string employeeName = "Rahul";
decimal salary = 45000.50m;
bool isActive = true;
Here, each variable has a specific data type that determines what kind of value it can hold.
intstores whole numbers.stringstores text.decimalis suitable for financial calculations that require decimal precision.boolstores eithertrueorfalse.
C# is a statically typed language. Once a variable has a type, you cannot assign a value of an incompatible type without an appropriate conversion.
int age = 25;
// Compilation error: a string cannot be assigned to an int.
age = "Twenty-five";
Understanding data types and variable declarations is essential because the compiler checks type compatibility before your application runs.
2. Understanding the var Keyword in C#
The var keyword allows C# to infer a variable's type from the expression used to initialize it. This feature is known as implicit typing.
Instead of explicitly writing the data type, you can let the compiler determine it.
var name = "Shreya";
var age = 24;
var salary = 45000.50m;
var isActive = true;
The compiler infers the following types:
| Declaration | Inferred Type |
|---|---|
var name = "Shreya"; | string |
var age = 24; | int |
var salary = 45000.50m; | decimal |
var isActive = true; | bool |
Although these declarations use var, they are still strongly typed. The compiler determines each type at compile time, not at runtime.
Can the Type of a var Variable Change?
No. Once the compiler infers the type, the variable remains that type.
var age = 25;
age = 30; // Valid
// age = "Thirty"; // Compilation error
The variable age is inferred as an int. Assigning another integer is valid, but assigning a string is not.
Why Is var Useful?
The var keyword is particularly helpful when the type is obvious from the assigned value or when the full type name would make the code unnecessarily lengthy.
var employee = new Employee();
var numbers = new List<int> { 10, 20, 30 };
It is also commonly used with LINQ queries and anonymous types.
var activeEmployees = employees
.Where(employee => employee.IsActive)
.ToList();
Here, var allows the compiler to infer the result's type without requiring you to write the entire generic collection type.
Best practice: Use var when it improves readability. If the inferred type is not obvious, an explicit type declaration can make your code easier to understand.
Can You Declare var Without an Initial Value?
No. A local variable declared using var must have an initializer so that the compiler can infer its type.
// Invalid
// var age;
// Valid
var age = 25;
This restriction ensures that the compiler knows the variable's type when it compiles the program.
3. Does C# Have a let Keyword Like JavaScript?
JavaScript developers often use let to declare variables whose values can change. C# does not have a direct equivalent of JavaScript's let keyword.
In C#, you normally declare a local variable using its explicit type or the var keyword.
JavaScript:
let age = 25;
age = 26;
C#:
int age = 25;
age = 26;
You can also use var:
var age = 25;
age = 26;
Both C# examples allow reassignment, but the variable's type remains fixed.
What About let in LINQ?
C# does use the contextual keyword let in query expressions. However, it serves a different purpose from JavaScript's variable declaration keyword.
var results =
from number in new[] { 10, 20, 30 }
let doubled = number * 2
select doubled;
The let keyword introduces a range variable within a LINQ query, allowing you to store an intermediate result for use in subsequent query clauses.
Remember: Use var or an explicit type for ordinary local variables in C#. Use let when you need to introduce an intermediate value inside a LINQ query expression.
4. Variable Naming Conventions in C#
Meaningful variable names make code easier to read, debug, and maintain. In professional C# projects, consistent naming conventions also help teams understand each other's code.
Consider these examples:
int x = 50000;
string n = "Rahul";
The code is valid, but the names do not explain what the values represent.
A clearer version is:
int employeeSalary = 50000;
string employeeName = "Rahul";
The second version communicates the purpose of each variable without requiring additional comments.
Common C# Naming Conventions
| Element | Recommended Convention | Example |
|---|---|---|
| Local variables | camelCase | employeeName |
| Method parameters | camelCase | customerId |
| Methods | PascalCase | GetEmployee() |
| Classes | PascalCase | EmployeeService |
| Constants | PascalCase | MaximumRetries |
| Private instance fields | Often _camelCase | _employeeRepository |
For example:
public class EmployeeService
{
private readonly int _departmentId;
public EmployeeService(int departmentId)
{
_departmentId = departmentId;
}
public string GetDepartmentName()
{
string departmentName = "Engineering";
return departmentName;
}
}
Here, EmployeeService follows PascalCase, _departmentId follows a common private-field convention, and departmentName follows camelCase.
These are established conventions rather than universal language requirements. Follow your project's existing style and configured .NET code-analysis rules.
5. What Is a Constant in C#?
A constant represents a value that must remain unchanged. In C#, the const keyword declares a compile-time constant.
Constants are useful for values such as fixed conversion factors, application-wide limits, or mathematical values that are known when the code is compiled.
For example:
const double Pi = 3.14159265359;
Console.WriteLine(Pi);
Output:
3.14159265359
Once declared, a constant cannot be assigned a different value.
const int MaximumAttempts = 3;
// Compilation error
// MaximumAttempts = 5;
Rules for const in C#
When using const, remember these important rules:
- A constant must be initialized when it is declared.
- Its value must be a compile-time constant.
- Its value cannot be changed after declaration.
- A local constant or a constant declared in a class is implicitly static.
- Constants are suitable for values that are genuinely fixed.
For example:
public class OrderSettings
{
public const int MaximumItems = 100;
public const string DefaultCurrency = "INR";
}
You can access these constants through the class name:
Console.WriteLine(OrderSettings.MaximumItems);
Console.WriteLine(OrderSettings.DefaultCurrency);
Important: Do not use const for values that may need to change through configuration, such as API endpoints, database connection strings, or deployment-specific settings.
6. What Is readonly in C#?
The readonly keyword is used with fields whose values should not be reassigned after initialization, except during permitted initialization stages.
Unlike const, a readonly field can receive its value at runtime. It can be initialized when declared or assigned inside an instance or static constructor, depending on whether the field is an instance or static field.
This makes readonly useful when a value is determined from configuration, constructor parameters, or runtime operations.
public class Employee
{
public readonly int EmployeeId;
public Employee(int employeeId)
{
EmployeeId = employeeId;
}
}
You can create an employee with a specific ID:
Employee employee = new Employee(101);
Console.WriteLine(employee.EmployeeId);
Output:
101
The constructor assigns the value when the object is created. After construction, ordinary code cannot reassign the readonly field.
Employee employee = new Employee(101);
// Compilation error
// employee.EmployeeId = 202;
Using readonly for Dependency Injection
In ASP.NET Core applications, readonly fields are frequently used to hold dependencies supplied through constructor injection.
public class ProductService
{
private readonly IProductRepository _productRepository;
public ProductService(IProductRepository productRepository)
{
_productRepository = productRepository;
}
public IEnumerable<Product> GetProducts()
{
return _productRepository.GetAll();
}
}
The constructor receives an IProductRepository implementation and stores it in a readonly field.
This prevents the field from being reassigned after initialization, helping keep the service's dependency reference consistent throughout its lifetime.
Note: A readonly reference does not make the referenced object immutable. The object itself may still be modified if its API allows it.
7. const vs readonly in C#
Although both keywords restrict reassignment, const and readonly serve different purposes.
| Feature | const | readonly |
|---|---|---|
| Value determined | At compile time | Can be determined at runtime |
| Initialization | Must be declared with a constant value | At declaration or in an appropriate constructor |
| Reassignment after initialization | Not allowed | Not allowed after permitted initialization |
| Declaration | Local variables and fields | Fields |
| Implicitly static | Yes | No |
| Can use constructor parameters | No | Yes |
| Common use case | Fixed mathematical values or stable constants | Object-specific values and injected dependencies |
Practical Example
public class ApplicationSettings
{
public const int MaximumLoginAttempts = 5;
public readonly string ApplicationName;
public ApplicationSettings(string applicationName)
{
ApplicationName = applicationName;
}
}
Usage:
ApplicationSettings settings =
new ApplicationSettings("Employee Portal");
Console.WriteLine(ApplicationSettings.MaximumLoginAttempts);
Console.WriteLine(settings.ApplicationName);
Output:
5
Employee Portal
The maximum number of login attempts is fixed at compile time, so const is appropriate. The application name is supplied when an object is created, so readonly is more suitable.
An Important Difference for Library Developers
Public constants deserve additional care when used in reusable libraries.
A const value is embedded into consuming assemblies when they compile against it. If a library changes that constant later, an already-compiled consumer may continue using the old value until it is recompiled.
A static readonly field can be a better choice when a value may change between library versions and consumers should read it from the updated library at runtime.
For example:
public static readonly int DefaultPageSize = 20;
Choose const for values that are genuinely fixed, and consider readonly when the value may evolve or must be determined at runtime.
8. Common Mistakes to Avoid
Beginners often understand variable declarations but overlook the differences between compile-time constants, runtime values, and naming conventions.
Here are some common mistakes to avoid:
Mistake 1: Declaring var without initialization
// Invalid
// var total;
Correction:
var total = 100;
Mistake 2: Assuming var makes a variable dynamically typed
var age = 25;
// Invalid: age is still an int.
// age = "Twenty-five";
Correction: Use the correct data type and convert values explicitly when necessary.
Mistake 3: Using const for a runtime value
// Invalid: DateTime.Now is evaluated at runtime.
// const DateTime currentTime = DateTime.Now;
Correction:
DateTime currentTime = DateTime.Now;
If the value should be captured once and not reassigned, a readonly field may also be appropriate.
Mistake 4: Assuming readonly makes an object immutable
A readonly reference prevents reassignment of that reference after initialization. It does not automatically prevent changes to the referenced object.
Mistake 5: Using unclear variable names
Prefer customerEmail over ce, and totalAmount over t, whenever the longer name improves readability.
9. Best Practices for Writing Clean C# Code
Follow these guidelines when working with variables and constants in production applications:
- Choose descriptive names: Make the purpose of each variable clear.
- Use
varthoughtfully: Prefer it when the inferred type is obvious or reduces unnecessary repetition. - Use explicit types when helpful: Improve readability when the assigned value does not clearly communicate the intended type.
- Use
constfor genuinely fixed values: Do not use it for data that must be evaluated at runtime. - Use
readonlyfor stable field references: This is particularly useful for dependencies injected through constructors. - Follow consistent naming conventions: Use camelCase for local variables and parameters and PascalCase for types and members.
- Avoid unnecessary mutable state: Keep variables' scopes and lifetimes as small as practical.
These practices help make C# applications easier to understand, test, and maintain as the codebase grows.
10. Frequently Asked Questions
1. What is the difference between a variable and a constant in C#?
A variable can generally be reassigned after declaration, while a constant declared with const cannot be changed after compilation. Use variables for changing data and constants for fixed values.
2. What does var mean in C#?
The var keyword tells the C# compiler to infer a local variable's type from its initialization expression. The variable remains strongly typed and cannot later hold an incompatible type.
3. Does C# support the let keyword?
C# does not use let as a general-purpose variable declaration keyword like JavaScript. It supports let within LINQ query expressions to introduce intermediate range variables.
4. What is the difference between const and readonly in C#?
const represents a compile-time constant, whereas readonly allows a field's value to be determined at runtime during initialization or construction. A readonly field cannot be reassigned through ordinary code after its permitted initialization stage.
5. Can a readonly field be assigned inside a constructor?
Yes. An instance readonly field can be assigned when declared or inside an instance constructor of its declaring type. A static readonly field can be assigned when declared or inside the appropriate static constructor.
6. Can var be used for class fields in C#?
No. The var keyword is used for local variable declarations and certain other language constructs, but not for declaring ordinary class fields. Class fields require an explicit type.
7. Which naming convention should I follow for C# variables?
Use camelCase for local variables and method parameters, such as employeeName. Use PascalCase for classes, methods, and constants, such as EmployeeService and MaximumAttempts.
8. Should I use const or readonly in ASP.NET Core?
Use const for values that are fixed at compile time. Use readonly for field references that should not be reassigned after initialization, including dependencies received through constructor injection. Use configuration for settings that vary across environments.
Key Takeaways
Variables and constants are essential to writing reliable C# applications. Understanding their differences helps you choose the right declaration for each situation.
- Use explicit types or
varto declare ordinary variables. - Remember that
varuses compile-time type inference; it does not make C# dynamically typed. - Use
constfor compile-time values that should never change. - Use
readonlyfor fields that can be initialized at runtime but should not be reassigned afterward. - Follow consistent naming conventions to improve code readability.
Next step: Practice these concepts in a small C# console application by declaring variables, changing their values, creating constants, and initializing readonly fields through constructors.
Continue learning with the C# Fundamentals roadmap.
Last updated 10/27/2026
Your notes
Sign in to save personal notes on this topic — they'll sync across your devices.
Was this tutorial helpful?
Help us create more free learning resources. Learn more
