C# Variables
Introduction
Variables are fundamental building blocks in any programming language, including C#. They act as containers that store data in a program's memory, allowing you to save, retrieve, and manipulate information while your application runs. In C#, variables are strongly typed, which means that each variable has a specific data type that determines what kind of data it can hold.
In this tutorial, we'll explore how variables work in C#, how to declare and initialize them, naming conventions, and best practices to follow when working with variables.
What are Variables?
A variable is essentially a name given to a memory location where data is stored. Think of variables as labeled boxes where you can put different types of information. In C#, each variable has:
- A name that you use to reference it
- A data type that defines what kind of data it can store
- A value that represents the actual data stored
Declaring Variables in C#
To create a variable in C#, you need to declare it by specifying its data type and name. The basic syntax is:
dataType variableName;
For example, to declare an integer variable named age
:
int age;
You can also initialize a variable (give it a value) when you declare it:
int age = 25;
Let's look at some examples of variable declarations with different data types:
// Numeric types
int count = 10; // Integer
double price = 15.99; // Double-precision floating point
float temperature = 98.6f; // Single-precision floating point
decimal money = 100.50m; // Decimal (note the 'm' suffix)
// Text type
string name = "John Doe"; // String of characters
// Single character type
char grade = 'A'; // Single character (note the single quotes)
// Boolean type
bool isActive = true; // Boolean (true or false)
// Date and time
DateTime today = DateTime.Now; // Current date and time
Example: Using Variables
Let's see a complete example of declaring variables and using them:
using System;
class Program
{
static void Main()
{
// Declaring variables
string studentName = "Maria Garcia";
int studentAge = 22;
double studentGPA = 3.8;
bool isEnrolled = true;
// Using variables in output
Console.WriteLine("Student Information:");
Console.WriteLine("------------------");
Console.WriteLine($"Name: {studentName}");
Console.WriteLine($"Age: {studentAge}");
Console.WriteLine($"GPA: {studentGPA}");
Console.WriteLine($"Currently Enrolled: {isEnrolled}");
}
}
Output:
Student Information:
------------------
Name: Maria Garcia
Age: 22
GPA: 3.8
Currently Enrolled: True
Variable Declaration Options
Multiple Variable Declaration
You can declare multiple variables of the same type in a single statement:
int x = 10, y = 20, z = 30;
Implicitly Typed Variables
C# allows you to use the var
keyword to declare variables without explicitly stating their type. The compiler infers the type from the initializer:
var message = "Hello World"; // Compiler infers string type
var number = 42; // Compiler infers int type
var price = 9.99; // Compiler infers double type
Note: When using var
, you must initialize the variable in the same statement since the compiler needs the initializer to determine the type.
Variable Naming Conventions in C#
Following proper naming conventions makes your code more readable and maintainable:
- Use camelCase for local variables and parameters (e.g.,
firstName
,totalAmount
) - Start with a letter or underscore (not a number)
- Use descriptive names that indicate the purpose of the variable
- Avoid reserved keywords and abbreviations
- Don't use Hungarian notation (prefixing variable names with type information)
Good variable names:
int age;
string firstName;
double taxRate;
bool isComplete;
Poor variable names:
int a; // Not descriptive
string str1; // Not descriptive
double d; // Not descriptive
bool b; // Not descriptive
string strName; // Hungarian notation (avoid)
Variable Scope
The scope of a variable determines where in your code the variable can be accessed:
Block Scope
Variables declared within code blocks (enclosed in {}
) are accessible only within that block:
void ExampleMethod()
{
// This variable is accessible throughout the method
int outerVariable = 10;
if (outerVariable > 5)
{
// This variable is only accessible within this if block
int innerVariable = 20;
Console.WriteLine(outerVariable); // Works fine
Console.WriteLine(innerVariable); // Works fine
}
Console.WriteLine(outerVariable); // Works fine
// Console.WriteLine(innerVariable); // Error! Not accessible here
}
Method-Level Variables (Local Variables)
Variables declared within a method are only accessible within that method:
void MethodOne()
{
int localVariable = 10; // Only accessible in MethodOne
Console.WriteLine(localVariable);
}
void MethodTwo()
{
// Console.WriteLine(localVariable); // Error! Not accessible here
}
Class-Level Variables (Fields)
Variables declared at the class level are accessible throughout the class (depending on their access modifiers):
class Student
{
// Class-level variable (field)
private string name;
public void SetName(string studentName)
{
name = studentName; // Can access the field
}
public void DisplayName()
{
Console.WriteLine(name); // Can access the field
}
}
Constants
If you have values that should never change during program execution, you can use constants:
const double Pi = 3.14159;
const string CompanyName = "Acme Corporation";
// Cannot be changed later in the program
// Pi = 3.14; // This would cause a compile error
Practical Example: Temperature Converter
Let's build a simple temperature converter that demonstrates the use of variables:
using System;
class TemperatureConverter
{
static void Main()
{
// Declare variables
double celsius, fahrenheit;
// Get input from user
Console.Write("Enter temperature in Celsius: ");
string input = Console.ReadLine();
// Convert input to double and store in variable
celsius = Convert.ToDouble(input);
// Calculate conversion using the variable
fahrenheit = (celsius * 9 / 5) + 32;
// Output the result using variables
Console.WriteLine($"{celsius}°C is equal to {fahrenheit}°F");
}
}
Example output:
Enter temperature in Celsius: 25
25°C is equal to 77°F
Variable Type Conversion
C# provides several ways to convert variables from one type to another:
Implicit Conversion
Automatic conversion happens when there's no risk of data loss:
int intNumber = 10;
double doubleNumber = intNumber; // Implicit conversion from int to double
Explicit Conversion (Casting)
Explicit casting is required when there's a risk of data loss:
double doubleNumber = 10.5;
int intNumber = (int)doubleNumber; // Explicit cast, intNumber becomes 10
Convert Class
The Convert
class provides methods for converting between types:
string stringValue = "42";
int intValue = Convert.ToInt32(stringValue);
double doubleValue = Convert.ToDouble(stringValue);
Parsing Methods
Type-specific parsing methods:
string stringValue = "42";
int intValue = int.Parse(stringValue);
TryParse for Safe Conversion
For safer conversions that handle potential errors:
string userInput = "abc";
int number;
if (int.TryParse(userInput, out number))
{
Console.WriteLine($"Parsed successfully: {number}");
}
else
{
Console.WriteLine("Could not parse the input as an integer");
}
Summary
In this tutorial, we've covered:
- What variables are and their role in C# programs
- How to declare and initialize variables with different data types
- Variable naming conventions and best practices
- Variable scope and accessibility
- Constants for immutable values
- Type conversion between different variable types
Variables form the foundation of any C# application. Mastering how to properly declare, initialize, and use variables is essential as you continue your journey in C# programming.
Additional Resources and Exercises
Practice Exercises
-
Basic Variables: Write a program that declares variables for your name, age, and favorite number. Display these values in a sentence.
-
Calculator: Create a simple calculator program that takes two numbers as input and outputs their sum, difference, product, and quotient.
-
Circle Calculations: Write a program that calculates the area and circumference of a circle based on a radius input from the user.
-
Temperature Converter: Extend the temperature converter example to convert from Fahrenheit to Celsius as well.
-
Type Conversion Challenge: Write a program that demonstrates all different ways of converting between types (implicit, explicit, Convert class, Parse methods, TryParse).
Further Reading
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)