Variables and Data Types
Explore the essential concepts of C# variables, data types, and arrays. Understand how to declare, initialize, and use variables, including primitive types and collections. Learn about the Common Type System which enables language interoperability in .NET, helping you write robust, type-safe code.
We'll cover the following...
Variables
No app is useful if it can’t store and process information. In this context, variables are important.
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.
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 objects represent text.
Remember that C# is case-sensitive, so the following two variable definitions represent two different variables:
string name;
string Name;
We’ve declared a variable, but it doesn’t contain any information yet. To assign a value to a variable, we use the assignment (=) operator.
name = "John";
We can combine declaration and assignment in one line. This operation is called initialization.
...