C# Constants, var Keyword, and Type Inference — Complete Beginner Guide
Learning Objectives
- Create compile time constants with const
- Use readonly fields for values set at creation
- Declare variables with var and type inference
- Know when explicit types are clearer
- Avoid common var mistakes
Why Constants Matter
Hardcoding the same value in many places makes programs brittle. If the value must change later you edit every copy. Constants give one named place for fixed values.
const double TaxRate = 0.18;
const int MaxLoginAttempts = 5;
double price = 1000;
double tax = price * TaxRate;
Console.WriteLine(tax);
const values are baked in at compile time. They must be initialized when declared and cannot change afterward.
const vs readonly
Both express immutability, but they work at different times.
| Keyword | When set | Where allowed |
|---|---|---|
| const | Compile time | Static members only |
| readonly | Runtime, often in constructor | Instance fields |
class Settings
{
const string AppName = "ChatWhole";
readonly DateTime CreatedAt;
public Settings()
{
CreatedAt = DateTime.Now;
}
}
Use const for numbers and text that never change. Use readonly when the value depends on runtime information known only at object creation.
Introducing var
The var keyword tells the compiler to figure out the type from the right side of the assignment. The variable still has a fixed type; only the spelling on the left is omitted.
var count = 10;
var price = 49.99;
var active = true;
var label = "Ready";
Console.WriteLine(count);
Console.WriteLine(price);
Console.WriteLine(active);
Console.WriteLine(label);
Here count becomes int, price becomes double, active becomes bool, and label becomes string.
How Type Inference Works
Type inference reads the expression on the right and assigns its type when you write var. The rule is simple: there must be something to infer.
var x = 5; // int
var y = 5.5; // double
var z = "text"; // string
// var w; // Error: no value to infer from
Once inferred, the type cannot change.
var n = 1;
// n = "hello"; // Error: n is int
n = 2; // OK
When var Helps
var shines when the type is obvious or the name is long.
var numbers = new List int();
var player = new Player();
var query = items.Where(i => i.Score > 10);
In these cases the right side already tells a clear story. Omitting the type reduces noise without hiding meaning.
When to Prefer Explicit Types
Write the type yourself when clarity matters more than brevity.
int retries = 3;
string userName = "Sam";
double balance = 250.00;
Also prefer explicit types when the right side is a literal that could be ambiguous, or when new team members benefit from seeing the type at a glance.
Common Mistakes
Assuming var means dynamic
var is not object. The type is fixed after assignment. Treating it like a container for any later value produces compile errors.
Using var with no initializer
// var temperature; // Not allowed
double temperature;
temperature = 30.5;
Ignoring readability
If a colleague cannot guess the type from context, spell the type out. Clarity beats cleverness in shared code.
Putting It Together
const int DaysInWeek = 7;
var daysLeft = DaysInWeek - 2;
var courseName = "C sharp Fundamentals";
var enrolled = true;
Console.WriteLine(courseName);
Console.WriteLine(daysLeft);
Console.WriteLine(enrolled);
Constants describe fixed rules. var keeps local code tidy. Together they make small programs easier to read.
Key Takeaways
💡
- const creates compile time constants that never change
- readonly fields are assigned once during object setup
- var infers the type from the value on the right
- Inferred types are still strongly typed and cannot change
- Choose explicit types whenever they improve clarity
Practice Questions
- What is the main difference between const and readonly?
- Does var create a dynamic variable that can hold any type later?
- Why is var w with no value illegal on its own line?
- Give two situations where writing the type explicitly is better.
- Declare a constant for pass mark and a var for a student score, then print whether the score meets the mark.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions