C# Variables
Variables are named memory regions in C# that allow users to store several values of the same datatype while the program is running. They serve as holding tanks for values. Before being used, all variables in C# must be declared. This declaration defines the data type, which dictates the kind and range of values the variable can hold, as well as the amount of memory that must be set aside.
Features of the Variables
Characteristics of variables include:
Name (identifier): a designation, like age, that designates the location of the memory.
Type: The type of data kept, such as int.
Value: actual data that is kept, such as 25.
Declaring Variables
Declaring a variable instructs the compiler to allot the required amount of memory with the given name and restricts access to that memory address to values of the designated data type. Although they can be declared inside any block or function or before a function as global variables, variables are usually declared at the start of the block or function.
Syntax for Declaration: datatype variableName;
Example:
int number; // Declares an integer variable named 'number'
string name; // Declares a string variable named 'name'
This instructs the compiler to use the name number to allocate memory for an integer value and to only permit integer values to enter that memory address.
Initializing and Assigning Values
The assignment operator = is used to store a value in a variable in order to assign a value to it. Setting a variable’s initial value at the moment of declaration is known as initialisation.
Syntax for Assignment: variable_name = value;
Syntax for Initialization: <data_type> <variable_name> = value;
Example:
int age; // Declaration
age = 25; // Assignment
string firstName = "John"; // Declaration and Initialization
int d = 3, f = 5; // Declares and initializes multiple variables
If no value is specified explicitly, C# data types all have a default value. For example, bool is set to false, string is set to null, and int is set to 0.
Rules for Creating Identifiers (Variable Names)
Entities such as variables, classes, or methods can be uniquely identified during program execution by using identifiers, which are user-defined names.
Rules::
- Contains only the underscore symbol (_), numeric digits (0–9), and letters (uppercase and lowercase).
- It can begin with a letter or an underscore, but it must not begin with a number.
- Special symbols (apart from underscores) shouldn’t be used.
- It cannot be a keyword in C#. Keywords may be used, though, if they are preceded by the @ symbol.
- Because C# is case-sensitive, age and age are two distinct variables.
- Even in a different code block, it is against the law to use the same name twice in a routine.
Example of Valid/Invalid Identifiers:
Valid: marks
, studentName
, _a
, pi
, value
.
Invalid: 123a
(beginning with a digit), break
(keyword), str-
(containing a special symbol), and a b
(containing whitespace).
Naming Recommendations
Be descriptive: Names ought to provide a clear explanation of the variable’s function, addressing the question of “what value is stored?” FirstName is superior to fn, for instance.
Concise: Just enough to make the objective clear, neither too long nor too short.
Follow conventions: For local variables and parameters, camelCase
is a popular convention (first word lowercase, subsequent words start with uppercase).
Boolean variables: Usually begins with is
, has
, or can
(e.g., canRead
, available
, isOpen
, valid
) and should imply truth or falsity.
Avoid digits or abbreviations: Generally speaking, if adding numbers or deleting vowels from names makes them less clear, do not do so.
Consistency: Whichever naming conventions are selected, they must be followed consistently throughout the project.
Variable Scope and Lifetime
The program’s scope specifies the section or sections in which a variable is available. Some examples of variables are:
Local variables: Declared inside a code block or procedure, and only available inside that block. From the declaration line to the block’s closing bracket, they are visible.
Instance variables (fields): They pertain to an object instance and are class attributes that are declared inside a class but outside of any methods or constructors. Their declaration marks the beginning of their scope, which concludes at the class’s closing curly bracket.
Static variables: Last the entire time the program is running and are connected to the class itself rather than a particular object.
A variable’s lifetime is the amount of time it stays in memory. It is advised to reduce variable scope and span (average lines between occurrences) in order to enhance the readability, maintainability, and quality of the code. Variables should ideally be defined as near to their initial use as feasible.
Code Examples: Basic Variable Declaration and Initialization
using System; // Keep only ONE 'using System;' at the very top of the file
public class VariableExample
{
// Renamed the Main method to a regular static method
// so it can be called from the main entry point (ScopeExample.Main).
public static void DemonstrateVariables()
{
Console.WriteLine("--- Variable Example Output ---");
// Declare and initialize an integer variable
// This is a 'value type' and its value is stored directly in the stack.
int age = 30;
Console.WriteLine("Age: " + age);
// Declare and initialize a string variable
// This is a 'reference type' and stores a reference to data on the heap.
string greeting = "Hello, C#!";
Console.WriteLine("Greeting: " + greeting);
// Declare a boolean variable
// 'bool' is a native Boolean data type.
// Its default value is 'false' if not initialized.
bool isLoggedIn = true;
Console.WriteLine("Is logged in: " + isLoggedIn);
// Character literal, enclosed in single quotes.
char initial = 'A';
Console.WriteLine("Initial: " + initial);
// Using different numeric types
float price = 19.99f; // float literal requires 'f' suffix
double gravity = 9.81; // double is default for real literals
decimal totalAmount = 12345.67m; // decimal literal requires 'm' suffix
Console.WriteLine("Price: " + price);
Console.WriteLine("Gravity: " + gravity);
Console.WriteLine("Total Amount: " + totalAmount);
// Object type can hold values of any other type.
// This implicitly performs 'boxing' if a value type is assigned.
object mixedData = "Some text";
Console.WriteLine("Mixed Data (string): " + mixedData);
mixedData = 12345;
Console.WriteLine("Mixed Data (int): " + mixedData);
Console.WriteLine(); // Add a blank line for readability
}
}
// Variable Scope and Assignment Example (This line is just a comment, no issue here)
public class ScopeExample
{
// Instance variable (field) - accessible by instance methods within the class
private int classValue = 10;
public void DemonstrateScope()
{
// Local variable - accessible only within this method
int methodValue = 20;
Console.WriteLine("Inside DemonstrateScope method:");
Console.WriteLine("Class Value (field): " + classValue);
Console.WriteLine("Method Value (local): " + methodValue);
if (methodValue > 15)
{
// Another local variable, scoped only to this 'if' block
int blockValue = 5;
Console.WriteLine("Block Value (local to if): " + blockValue);
}
// blockValue is NOT accessible here.
// Reassigning classValue (modifies the instance field)
classValue = 100;
Console.WriteLine(); // Add a blank line for readability
}
// This is the single entry point for the application
public static void Main(string[] args)
{
// Call the demonstration for variables
VariableExample.DemonstrateVariables();
Console.WriteLine("--- Scope Example Output ---");
ScopeExample obj = new ScopeExample(); // Create an object instance
Console.WriteLine("Initial classValue: " + obj.classValue); // Access instance field
obj.DemonstrateScope(); // Call instance method
Console.WriteLine("Updated classValue after method call: " + obj.classValue);
// This would cause a compile-time error because methodValue is local to DemonstrateScope()
// Console.WriteLine(methodValue);
}
}
Output
--- Variable Example Output ---
Age: 30
Greeting: Hello, C#!
Is logged in: True
Initial: A
Price: 19.99
Gravity: 9.81
Total Amount: 12345.67
Mixed Data (string): Some text
Mixed Data (int): 12345
--- Scope Example Output ---
Initial classValue: 10
Inside DemonstrateScope method:
Class Value (field): 10
Method Value (local): 20
Block Value (local to if): 5
Updated classValue after method call: 100
You can also read Data Types In C#: Building Blocks Of Your Applications