In C#, variables are used to store data in memory. They are a fundamental aspect of programming and can hold various types of data, including integers, floating-point numbers, characters, and more. This tutorial covers variable declaration, initialization, data types, scope, and best practices in C#.
Variable declaration specifies the name and type of the variable, while initialization assigns a value to the variable. You can declare and initialize variables in a single statement.
Basic Example:
using System;
namespace VariableExample
class Program
{
static void Main(string[] args)
{
// Variable declaration
int age;
// Variable initialization
age = 30;
// Combined declaration and initialization
string name = "John";
bool isStudent = false;
double salary = 3000.50;
Console.WriteLine($"Name: {name}, Age: {age}, Student: {isStudent}, Salary: {salary}");
}
}
using System;
namespace VariableExample
class Program
{
static void Main(string[] args)
{
// Variable declaration and initialization
var age = 30; // int type inferred
var name = "John"; // string type inferred
var isStudent = false; // bool type inferred
var salary = 3000.50; // double type inferred
// Local function with variable declaration and initialization
void DisplayDetails()
{
var details = $"{name}, Age: {age}, Student: {isStudent}, Salary: {salary}";
Console.WriteLine(details);
}
// Calling the local function
DisplayDetails();
}
}
C# supports various data types, including primitive types (such as int, float, and bool) and complex types (such as arrays and classes). Choosing the appropriate data type is crucial for efficient memory usage and performance.
2.1 Primitive Data TypesPrimitive data types are the basic types built into the language. They include integers, floating-point numbers, characters, and boolean values.
Basic Example:
using System;
namespace PrimitiveDataTypes
class Program
{
static void Main(string[] args)
{
int age = 30; // 32-bit signed integer
float height = 5.9f; // 32-bit floating-point
char initial = 'J'; // Single 16-bit Unicode character
bool isStudent = false; // Boolean value (true or false)
Console.WriteLine($"Age: {age}, Height: {height}, Initial: {initial}, Student: {isStudent}");
}
}
using System;
namespace PrimitiveDataTypes
class Program
{
static void Main(string[] args)
{
// Arithmetic operations with primitive data types
int a = 10, b = 20;
int sum = a + b;
int difference = a - b;
int product = a * b;
int quotient = a / b;
// Combining boolean and char data types
bool isEqual = a == b;
char grade = isEqual ? 'A' : 'B';
Console.WriteLine($"Sum: {sum}, Difference: {difference}, Product: {product}, Quotient: {quotient}");
Console.WriteLine($"Are a and b equal? {isEqual}");
Console.WriteLine($"Assigned Grade: {grade}");
}
}
Complex data types include arrays, classes, and structs. They allow you to store collections of data and create custom types.
Basic Example:
using System;
namespace ComplexDataTypes
class Program
{
static void Main(string[] args)
{
// Array of integers
int[] numbers = { 1, 2, 3, 4, 5 };
// Instance of a class
Person person = new Person
{
Name = "John",
Age = 30
};
Console.WriteLine($"Person: {person.Name}, Age: {person.Age}");
Console.WriteLine("Numbers:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
using System;
using System.Collections.Generic;
namespace ComplexDataTypes
class Program
{
static void Main(string[] args)
{
// Dictionary to store Person objects
Dictionary<string, Person> people = new Dictionary<string, Person>
{
{ "John", new Person { Name = "John", Age = 30 } },
{ "Jane", new Person { Name = "Jane", Age = 25 } }
};
// Manipulating and accessing complex data types
foreach (var key in people.Keys)
{
var person = people[key];
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
The scope of a variable determines where it can be accessed within the code. C# supports block scope, method scope, and class scope.
3.1 Block ScopeA variable declared within a block (e.g., inside a loop or a conditional statement) is only accessible within that block.
Basic Example:
using System;
namespace BlockScope
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
int loopVariable = i * 2;
Console.WriteLine($"Loop Variable: {loopVariable}");
}
// loopVariable is not accessible here
// Console.WriteLine(loopVariable); // Uncommenting this line would cause a compile-time error
}
}
using System;
namespace BlockScope
class Program
{
static void Main(string[] args)
{
// Block scope with nested loops
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
int product = i * j;
Console.WriteLine($"i: {i}, j: {j}, Product: {product}");
}
}
}
}
A variable declared within a method is only accessible within that method.
Basic Example:
using System;
namespace MethodScope
class Program
{
static void Main(string[] args)
{
int result = Add(5, 3);
Console.WriteLine($"Result: {result}");
}
static int Add(int a, int b)
{
int sum = a + b;
return sum;
}
}
using System;
namespace MethodScope
class Program
{
static void Main(string[] args)
{
int result = MultiplyAndAdd(5, 3, 2);
Console.WriteLine($"Result: {result}");
}
static int MultiplyAndAdd(int a, int b, int multiplier)
{
int product = a * b;
int result = product + multiplier;
return result;
}
}
A variable declared at the class level (e.g., as a field or property) is accessible throughout the class. Fields are variables declared directly in a class, while properties are members that provide a flexible mechanism to read, write, or compute the values of private fields.
Basic Example:
using System;
namespace ClassScope
class Person
{
// Fields
private string name;
private int age;
// Properties
public string Name
{
get => name;
set => name = value;
}
public int Age
{
get => age;
set => age = value;
}
public string FullName { get; set; }
public void Introduce()
{
Console.WriteLine($"Hi, my name is {Name} and I am {Age} years old.{FullName}");
}
}
class Program
{
static void Main(string[] args)
{
Person person = new Person
{
Name = "John",
Age = 30
};
person.Introduce();
}
}
using System;
namespace ClassScope
class Person
{
// Fields
private string name;
private int age;
private string occupation;
// Properties
public string Name
{
get => name;
set => name = value;
}
public int Age
{
get => age;
set => age = value;
}
public string Occupation
{
get => occupation;
set => occupation = value;
}
public void Introduce()
{
Console.WriteLine($"Hi, my name is {Name}, I am {Age} years old, and I am a {Occupation}.");
}
}
class Program
{
static void Main(string[] args)
{
Person person = new Person
{
Name = "John",
Age = 30,
Occupation = "Software Developer"
};
person.Introduce();
// Updating fields through properties
person.Occupation = "Senior Developer";
person.Introduce();
}
}
Understanding and applying best practices in variable declaration and initialization are crucial for writing clean, efficient, and maintainable C# code. By following the guidelines outlined in this tutorial, you can ensure that your variables are well-managed and your code is of high quality.