Variables and Data Types
Explore how to create and use variables, including naming rules, assignment, and initialization in C#. Understand primitive types, type inference with var, and work with arrays. This lesson helps you grasp C# fundamentals essential for writing reliable and readable code using .NET's type system.
Applications need to store and process information. Variables provide a way to do this.
Variables
Variables are used to store data within a program. They represent a named area of computer memory that holds a value of a particular type. The type determines what kind of information a variable can store.
The basic syntax for declaring a variable is as follows:
variable_type variable_name;
Valid variable names must meet the following requirements:
The name can contain an underscore and any number and letter, while the first character in the name must be a letter or underscore.
The name can’t contain punctuation marks or spaces.
We can’t use a C# keyword as a variable name (unless we prefix it with
@, though this is rare).
Although we can give any name to our C# variables, it’s highly recommended to use descriptive names. For instance, if we want to store a person’s first name, we can declare a variable as follows:
string name;
In the example above, we create a variable called name that has the string type. The string type represents text.
Case sensitivity
C# is case-sensitive. This means that depending on the character case, the same names can represent different classes, methods, and variables.
For instance, in the following code, we have a string variable named name. We can create another string variable just below and name it Name.
string name;string Name;
name = "John";
We can combine declaration and ...