Practical examples of C# variable declaration and initialization examples
Straightforward examples of C# variable declaration and initialization examples
Let’s start with the kind of code you actually write in everyday C#—simple, explicit declarations with immediate initialization.
// Explicit type with initialization
int age = 32;
string firstName = "Jordan";
bool isActive = true;
// Multiple declarations on separate lines (preferred for readability)
double price = 19.99;
double taxRate = 0.07;
// Char and decimal (often used for money)
char grade = 'A';
decimal accountBalance = 1500.75m; // note the 'm' suffix
These are the best examples to start with because they keep type information visible. In team codebases, explicit types like this make intent obvious when you skim a file or review a pull request.
Modern C# encourages you to both declare and initialize variables in the same statement whenever you can. It reduces the chance of using a variable before it’s assigned and makes the flow easier to follow.
Using var: type inference examples include local variables and LINQ
One of the most common examples of C# variable declaration and initialization examples in real projects uses var for local variables. The compiler infers the type from the right-hand side.
var count = 10; // inferred as int
var name = "Alex"; // inferred as string
var isEnabled = false; // inferred as bool
var price = 19.99m; // inferred as decimal
var really shines when the type is obvious from context or annoyingly long to spell out.
// Without var
Dictionary<string, List<int>> scoresByUser = new Dictionary<string, List<int>>();
// With var (same result, easier to read)
var scoresByUser = new Dictionary<string, List<int>>();
In LINQ-heavy code, var is almost standard:
var highScores = scoresByUser
.Where(kvp => kvp.Value.Average() >= 90)
.Select(kvp => kvp.Key)
.ToList();
The best examples of var usage follow a simple rule: if the inferred type is clear to a human reader, var is fine. If the type would be surprising, prefer an explicit type.
Examples of C# variable declaration and initialization examples with nullable and non-nullable types
Since C# 8, nullable reference types are on by default in many new .NET templates, and that changes how you think about variable declaration and initialization.
string firstName = "Jordan"; // non-nullable, must not be null
string? middleName = null; // nullable, can be null
When you declare a non-nullable variable, the compiler expects that it will never be null at runtime. That means you should initialize it with a non-null value or assign a non-null value before first use.
A real example of this in a class:
public class Customer
{
public string Id { get; } // non-nullable
public string Name { get; set; } // non-nullable
public string? Notes { get; set; } // nullable
public Customer(string id, string name)
{
Id = id ?? throw new ArgumentNullException(nameof(id));
Name = name ?? throw new ArgumentNullException(nameof(name));
}
}
Here you see multiple examples of C# variable declaration and initialization examples:
- Auto-properties with default initialization rules
- Constructor parameters assigned to read-only properties
- Nullable vs. non-nullable design to convey intent
For more background on nullable reference types and why they were added, the official .NET docs are worth a read: https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references
Field, property, and constant examples of C# variable declaration and initialization
Local variables are only half the story. In real-world C# code, you spend a lot of time declaring fields, properties, and constants.
Fields and auto-properties
public class Order
{
// Field with initialization
private readonly DateTime _createdAt = DateTime.UtcNow;
// Auto-property with default value
public string Status { get; private set; } = "Pending";
// Auto-property without default; must be set later
public decimal Total { get; private set; }
public Order(decimal total)
{
Total = total;
}
}
This class gives clear examples of C# variable declaration and initialization examples at the class level:
- A
readonlyfield initialized at declaration - An auto-property with an initializer
- An auto-property initialized in the constructor
Constants and readonly fields
public class MathConfig
{
public const double Pi = 3.141592653589793;
public readonly int MaxIterations;
public MathConfig(int maxIterations)
{
MaxIterations = maxIterations;
}
}
const values are compile-time constants and must be initialized where they are declared. readonly fields can be initialized either at declaration or in a constructor, giving you more flexibility.
Real examples of C# variable declaration and initialization in methods
Inside methods, you often declare variables that represent inputs, intermediate results, and outputs. Here’s a realistic service-style method from a modern .NET API:
public async Task<UserProfile> GetUserProfileAsync(string userId)
{
if (string.IsNullOrWhiteSpace(userId))
{
throw new ArgumentException("User ID is required", nameof(userId));
}
var stopwatch = Stopwatch.StartNew();
// Local variable with await result
UserEntity? userEntity = await _userRepository.GetByIdAsync(userId);
if (userEntity is null)
{
throw new KeyNotFoundException($"User '{userId}' not found.");
}
var profile = new UserProfile
{
Id = userEntity.Id,
DisplayName = userEntity.DisplayName,
Email = userEntity.Email,
CreatedAt = userEntity.CreatedAt
};
stopwatch.Stop();
_logger.LogInformation("Loaded profile for {UserId} in {ElapsedMs} ms", userId, stopwatch.ElapsedMilliseconds);
return profile;
}
This snippet packs several examples of C# variable declaration and initialization examples into one real-world method:
- Parameter
string userIdas an input variable stopwatchdeclared and initialized via a factory method- Nullable local
UserEntity? userEntityfrom an async call profileas an object initializer
These are the kinds of patterns you see in production APIs running on .NET 6, 7, and 8.
Pattern matching and out parameter examples include modern C# syntax
Modern C# leans heavily on pattern matching and out variables, which provide some of the best examples of C# variable declaration and initialization examples in compact form.
out variables
if (int.TryParse(input, out int value))
{
Console.WriteLine($"Parsed value: {value}");
}
else
{
Console.WriteLine("Invalid number");
}
Here, value is declared and initialized inside the if condition. Before C# 7, you had to declare it on a separate line, which made code noisier.
Pattern matching with declaration
object result = GetResult();
if (result is int intResult)
{
Console.WriteLine($"Integer: {intResult}");
}
else if (result is string text)
{
Console.WriteLine($"String: {text}");
}
The intResult and text variables are both declared and initialized only when the pattern matches. This style is common in modern codebases and is worth practicing as part of your own set of examples of C# variable declaration and initialization examples.
Examples of C# variable declaration and initialization with collections and new()
C# 9 and later added target-typed new, which shows up constantly in 2024-era code.
// Older style
List<string> names = new List<string>();
// Modern style with target-typed new
List<string> modernNames = new();
// Using collection initializer
var scores = new List<int> { 90, 85, 100 };
// Dictionary with initializer
Dictionary<string, int> inventory = new()
{
["Apples"] = 25,
["Oranges"] = 40
};
These are real examples of C# variable declaration and initialization examples you’ll see in open-source .NET projects on GitHub. They keep the code shorter without sacrificing clarity.
Async, using, and await – modern control-flow examples
C# 8+ also introduced using declarations, which combine resource management with variable declaration.
using var httpClient = new HttpClient();
var response = await httpClient.GetAsync("https://example.com");
string content = await response.Content.ReadAsStringAsync();
Here you get a trio of modern examples of C# variable declaration and initialization examples:
using var httpClientdeclares and initializes a disposable resourceresponseandcontentare local variables initialized with awaited results
This pattern shows up in microservices, desktop apps, and even console utilities built on .NET 8.
Style tips and best examples to copy in your own code
If you’re trying to build a mental library of the best examples of C# variable declaration and initialization examples to follow, a few patterns stand out:
- Prefer declaring and initializing on the same line when possible.
- Use explicit types when the type might surprise the reader.
- Use
varwhen the type is obvious or overly verbose. - For fields and properties, initialize at declaration or in constructors so objects are always in a valid state.
- Use nullable reference types (
string?) only whennullis truly a valid and expected value. - Favor object and collection initializers for configuration-like data.
If you’re working in a team, it’s worth agreeing on shared style rules and enabling analyzers. Microsoft’s coding conventions for C# provide a helpful baseline: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions
FAQ: common questions and examples of C# variable usage
What is an example of declaring and initializing a variable in one line?
A simple example of C# variable declaration and initialization is:
int temperatureFahrenheit = 72;
You declare the type (int), give it a name (temperatureFahrenheit), and assign a value (72) in a single statement.
Can I declare a variable without initializing it in C#?
For local variables, you can declare without initializing:
int result;
// ... some logic
result = 10;
However, the compiler will not let you read result before you assign a value. For fields, auto-properties, and properties with backing fields, the runtime provides default values (for example, 0 for int, null for reference types), but most style guides encourage explicit initialization when it matters.
What are some examples of using var versus explicit types?
Use var when the type is obvious:
var total = 100m; // decimal is clear from the 'm'
var user = new User("id", "name");
Use explicit types when it aids readability:
Dictionary<string, int> counts = GetCounts();
Both patterns are valid examples of C# variable declaration and initialization examples; the choice is about clarity for future readers.
How do I declare constants and read-only variables in C#?
A constant must be initialized where it’s declared:
public const int MaxRetries = 3;
A readonly field can be initialized at declaration or in a constructor:
public readonly Guid Id = Guid.NewGuid();
These are real examples of C# variable declaration and initialization that protect values from unintended changes.
Where can I learn more about C# language features?
The official Microsoft documentation is the best primary source for C# language details and updated examples:
- C# language documentation: https://learn.microsoft.com/en-us/dotnet/csharp/
- C# programming guide: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/
Even if you learn primarily from examples of C# variable declaration and initialization examples like the ones above, pairing them with the official docs will give you a stronger understanding of why the language behaves the way it does.
Related Topics
Practical examples of polymorphism in C++: function overloading
Best examples of dynamic memory allocation in C++: new and delete
Practical examples of C# variable declaration and initialization examples
Modern examples of C++ operator overloading: custom operators examples that actually matter
Best examples of C# conditional statements: examples & explanations
Real‑world examples of C# exception handling: 3 practical patterns every developer should know
Explore More C++ Code Snippets
Discover more examples and insights in this category.
View All C++ Code Snippets