C# variables act as storage units for holding data while the program is running. They symbolize specific memory addresses and are essential for allocating memory to store information while the program is in operation. Variables allow for dynamic data manipulation throughout the program's execution.
Syntax:
It has the following syntax:
type variableName = value;
Where,
- type: It represents the data type, such as int, float, and char.
- VariableName: It defines the variable name.
- Value: It represents the value of the variable.
Simple Example of C# Variables:
Let's consider a basic example to demonstrate the concept of variables in C#.
Example
using System;
public class Variables_Declaration
{
public static void Main(string[] args)
{
int num = 5; // Integer value
string name = "John"; //string value
Console.WriteLine("The number is " +num);
Console.WriteLine("Name is " +name);
}
}
Output:
The number is 5
Name is John
Explanation:
In this instance, we have initialized two variables: num, defined as an integer set to 5, and name, defined as a string set to "John". Subsequently, the script displays both values by invoking the Console.WriteLine function.
Now, we will explore the process of declaring a variable, assigning an initial value to a variable, retrieving the value of a variable, and modifying the value of a variable step by step.
1) Creating a Variable
When working with C#, it is essential to define the data type and provide an initial value when declaring a variable.
Syntax
It has the following syntax:
type VariableName;
Where,
- datatype: This specifies the kind of data that a variable can hold.
- VariableName: This denotes the name given to the variable.
Example:
int sum;
In this instance, we employ the int data type to retain the whole number value.
2) Variable Initialization
In C#, the concept of initialization refers to assigning a value to a variable, which is the primary purpose of the variable. This process involves using the assignment operator (=). Below is the syntax for variable initialization:
type variable_name;
variable_name = value;
Example:
int num; // declaring variable num
num=20; // Initializing num with value 20
In this instance, we utilize the integer data type to allocate and store a set of 20 numerical values.
3) Variable Accessing
In C#, accessing a variable involves retrieving or changing the stored value within the variable. It can be likened to a receptacle for holding various items that can be retrieved as required.
C# Variable Accessing Example
Let's consider a scenario to demonstrate how to retrieve a variable in C#.
Example
using System;
public class AccessingValues
{
public static void Main(string[] args)
{
int roll_no = 10;
string name = "John";
float total_marks = 123f;
Console.WriteLine("Roll Number is \n" + roll_no + "\nName is \n" + name + "\nTotal Marks are:\n" + total_marks);
}
}
Output:
Roll Number is
10
Name is
John
Total Marks are
123
Explanation:
In this instance, we've defined and set values for three variables (rollno, name, and totalmarks) containing student information. Subsequently, the Console.WriteLine function is employed to display each variable along with relevant text on separate lines.
4) Updating a Variable:
Let's consider a scenario to demonstrate the process of modifying a variable in C#.
Example
using System;
public class Updates
{
public static void Main(string[] args)
{
int value= 15;
Console.WriteLine("The entered the value is " +value);
value= 25;
Console.WriteLine("The updated value is " + value);
}
}
Output:
The entered the value is 15
The updated value is 25
Explanation:
In this instance, an integer variable named value is initialized with a value of 15 and then outputted. Subsequently, the value is modified to 25, and the updated value is showcased.
Rules for Creating a Variable
In C#, if we want to create a variable, we have to follow the following rules. These are as follows:
- Variable names should be case-sensitive.
- Variable names must start with an alphabet. It can be alpha-numeric.
- We cannot write the special symbol. Only underscore (_) is allowed.
- We can't use a keyword name as a variable.
- We have used a limited number of characters in a variable name. Usually, variable names are sufficient between 10 to 12 characters.
- We used the comma (,) symbol to create more than one variable.
- Wide space is not allowed between variable names.
Types of Variable in C#
In C#, there exist five categories of Variables. These include:
The CSS code snippet below illustrates the styling for a placeholder diagram:
.placeholder-diagram { background: linear-gradient(135deg, #374151 0%, #1f2937 100%); border-radius: 12px; padding: 40px; margin: 20px 0; text-align: center; }
.placeholder-diagram .placeholder-icon { font-size: 3rem; margin-bottom: 10px; }
.placeholder-diagram .placeholder-text { color: #9ca3af; font-size: 1rem; }
Here, we will discuss these variables one by one.
1) Local Variables
In C#, local variables refer to variables that are declared within a method or constructor block. These variables are only accessible within the specific block and not outside the constructor.
C# Local Variables Example
Let's consider an example to demonstrate a local variable in C#.
Example
using System;
class Program
{
static void Main()
{
int number = 100; // Local variable
Console.WriteLine("The entered number is " +number);
}
}
Output:
The entered number is 100
Explanation:
In this instance, an integer value representing a local variable is utilized. Subsequently, the Console.WriteLine method is employed to display the result.
2) Instance Variable or Non-Static Variables:
In C#, instance variables are alternatively referred to as non-static variables, which are defined within a class but outside of any method, constructor, or block. These variables are activated upon the instantiation of a class object. Access specifiers can be employed to establish an instance variable.
C# Instance Variable Example
Let's consider an example to demonstrate the concept of an instance variable in C#.
Example
using System;
class Records {
string name; // Instance Variable
int Marks;
string performance;
// Main Method
public static void Main(String[] args)
{
Records obj = new Records(); // create the object of the class
obj.name = "John";
obj.Marks = 95;
obj.performance = "Excellent";
// showing the records of student
Console.WriteLine("Record of Students is ");
Console.WriteLine("The name of the student is " + obj.name);
Console.WriteLine("The mark of student is " +obj.Marks);
Console.WriteLine("The performance of the student is " +obj.performance);
}
}
Output:
Record of Students is
The name of Student is John
The mark of Student is 95
The performance of the student is Excellent
Explanation:
In this instance, we declare variables of integer and string data types within the class. Subsequently, we instantiate an object of the class to construct the program.
3) Static Variable or Class Variables:
In C#, static variables are alternatively referred to as class variables, which are defined within a class but outside of any method, constructor, or block. These variables behave similarly to instance variables. The static keyword is employed to define static variables. Unlike instance variables, objects cannot be instantiated for static variables while the program is running.
C# Static Variables Example
Let's consider an example to demonstrate the concept of a static variable in C#.
Example
using System;
class Employee {
static int num; // integer variable
static string name = "John";
public static void Main(String[] args)
{
Employee.num = 950; // Accessing the variable
Console.WriteLine(Employee.name + "'s total marks is " + Employee.num);
}
}
Output:
John's total marks is 950
Explanation:
In this instance, we define static variables of integer and string types within the class. Subsequently, we retrieve these static variables within the main method.
5) Constant Variable:
In C#, constant variables are defined using the const keyword. These variables are immutable and cannot be modified after initialization.
C# Constant Variable Example
Let's consider an example to demonstrate the use of a constant variable in C#.
Example
using System;
class Program
{
const int number = 100; // constant variable
static void Main()
{
Console.WriteLine("The number is " + number);
}
}
Output:
The number is: 100
Explanation:
In this instance, a constant variable is established and its value is retrieved within the main function.
Readonly Variables:
In C#, constants are defined using the readonly keyword, which ensures that their value cannot be altered after initialization. It is important to note that a readonly variable does not have to be initialized when declared; it can also be initialized within the constructor if needed.
C# Readonly Variables Example
Let's consider a scenario to demonstrate the readonly variable in C#.
Example
using System;
class Program {
static int number = 400;
readonly int num1;
public static void Main()
{
Program obj = new Program();
Console.WriteLine("The value of b is = " + Program.number);
Console.WriteLine("The value of k is = " + obj.num1);
}
}
Output:
The value of b is = 400
The value of k is = 0
Explanation:
In this instance, a static variable is employed, shared among all objects, and set to 400 initially. Subsequently, the num1 variable, marked as readonly, defaults to 0 since no specific value is assigned to it.
Scope of Variables
In C#, the range of variables determines the accessibility of the variable within a particular part of the program. There are primarily three categories of variable scopes in C#.
The given CSS code snippet defines the styling for a placeholder diagram. The diagram has a background with a gradient color scheme, a border with rounded corners, padding, margin, and center-aligned text. The placeholder icon within the diagram is styled with a specific font size and margin, while the placeholder text has a defined color and font size.
Here, we will explore the extent of variables in C# individually.
Class Level Scope
In C#, class-level scope pertains to variables declared within the class but outside of methods and constructors, granting accessibility throughout the entire class in the program. These variables can be accessed through non-static methods within the class where they are defined.
C# Class Level Scope Variable Example
Let's consider an example to demonstrate the class-level scope variable in C#.
Example
using System;
public class Example
{
int number = 50; // class-level variable
public void show()
{
Console.WriteLine("Number is " + number); // accessing class-level variable
}
}
public class Program
{
public static void Main()
{
Example s = new Example();
s.show();
}
}
Output:
Number is 50
Explanation:
In this instance, we are working with the class-level variable (number=50). Subsequently, we define the Show method, which accesses the variable.
Method-Level Scope
In C#, method-level scope pertains to variables declared within the method (function). These are commonly referred to as local variables, and they are inaccessible outside of the method.
C# Method-Level Scope Example
Let's consider an example to demonstrate the scope of method-level variables in C#.
Example
using System;
class Example
{
static void Main()
{
int num = 1000; // Method-level variable
Console.WriteLine("The number is " + num);
}
}
Output:
The number is 1000
Explanation:
In this instance, we demonstrate the local variable within a method by initializing an integer as num=1000. Subsequently, the result is displayed using the Console.WriteLine method.
Code-Block Level Scope:
In C#, code-block level scope implies that a variable is limited to the block of code where it is declared, restricting its access outside of that specific block.
C# Code-Block Level Scope Example
Let's consider an example to demonstrate the scope of variables at the code block level in C#.
Example
using System;
public class Num
{
public static void Main() {
Num obj = new Num();
obj.showNum();
}
void showNum() {
for (int i = 0; i < 5; i++) {
Console.WriteLine(i); // 'i' is exist here
}
// Console.WriteLine(i); // Error: 'i' does not exist here
}
}
Output:
0
1
2
3
4
Explanation:
In this instance, we are focusing on the scope of the code block 'i', which is where the variable is defined within the 'for' loop. Subsequently, an instance will be generated to call the function.
Conclusion
In C#, variables play a fundamental role for developers when building software applications. They serve as essential elements in the development process, acting as containers that store memory locations. There are five primary types of variables in C#: local, instance, static, constant, and read-only. Each type fulfills important functions within the realm of programming.
C# Variables FAQs
- What is the Variable?
C# variables act as storage units for holding data throughout the program's runtime, symbolizing specific memory addresses.
- Is it possible to alter constant values in C#?
No, the unchanging value remains consistent regardless of the circumstances. Constant values are immutable once assigned and cannot be altered.
- Is it possible to declare a Variable without initializing it with a value?
Yes, it is possible to define a variable without assigning it a value.
- Is it permissible to modify the data type of a variable post declaration?
No, it is not possible to modify variables once they have been declared.
- Does the casing of variables matter?
Yes, variables are case-sensitive; for instance, "Name" and "name" are distinct.