Variables are fundamental components in programming that store and manage data within a program. In C#, variables are strongly typed, meaning the data type of a variable must be declared before assigning a value to it. This tutorial will provide a basic understanding of C# variables.
1. Variable Declaration and Initialization
- Declaration: Variables in C# are declared by specifying the data type followed by the variable name.
- Initialization: Variables can be initialized (assigned a value) at the time of declaration or later.
Have a look in the following example:
int number; // Declaration
number = 10; // Initialization
2. Data Types
- Numeric Types:
int
,double
,float
,decimal
, etc. - Boolean Types:
bool
(true/false). - Character Types:
char
(a single character). - String Type:
string
(a sequence of characters). - Others:
object
,dynamic
, etc.
int age = 30; // Integer
double pi = 3.14; // Double
bool isValid = true; // Boolean
string name = "John"; // String
3. Variable Scope
- Local Variables: Defined within a method and can only be used within that method.
- Global Variables: Defined at the class level and accessible throughout the class.
class MyClass
{
int x = 10; // Global Variable
void MyMethod()
{
int y = 20; // Local Variable
}
}
4. Constants
const
keyword is used to declare constants that cannot be changed.- Constants must be initialized when declared.
const int hoursInDay = 24;
5. Naming Conventions
- Variable names should be meaningful and follow naming conventions (camelCase in C#).
- Names should start with a letter and not contain spaces or special characters.
int numberOfStudents = 50;
string userName = "Alice";
6. Summary
- Variables store data, allowing you to work with information in a program.
- C# variables are declared with a specific data type and follow specific naming conventions.
Understanding C# variables is an essential step in learning the language and creating functional applications. This guide provides a starting point to help you grasp the basics of variable usage in C#.