Variables in C#
Variables are fundamental building blocks in C# programming. They allow you to store and manipulate data in your programs. This section will cover various aspects of variables in C#.
Declaring Variables
In C#, variables must be declared before they can be used. The basic syntax for declaring a variable is:
dataType variableName;
Where dataType
is the type of data the variable will hold, and variableName
is the name you choose for the variable.
Variable names in C# are typically camel-cased (e.g. int thisIsCamelCase;
).
Here are some examples of variable declarations:
int age;
string name;
double salary;
bool isEmployed;
You can also declare multiple variables of the same type in a single line (🌶️🌶️🌶️ Spencer doesn't really do this, ever):
int x, y, z;
Initializing Variables
You can initialize a variable at the time of declaration:
int age = 25;
string name = "John Doe";
double salary = 50000.50;
bool isEmployed = true;
C# also supports type inference using the var
keyword. The compiler will infer the type based on the assigned value:
var count = 10; // int
var message = "Hello, World!"; // string
var pi = 3.14159; // double
🌶️🌶️🌶️ Spencer almost exclusively uses var
, except...
You can also set the type of a variable to a type in the object's inheritance chain:
object thisIsAString = "told you";
(We'll discuss this more as we discuss inheritance more.)
Constants
Constants are variables whose values cannot be changed once they are assigned. They are declared using the const
keyword:
const int MaxScore = 100;
const string CompanyName = "Acme Corp";
Variable Scope
The scope of a variable determines where in your code the variable can be accessed. C# has several levels of scope:
- Block scope
- Method scope
- Class scope
We'll cover these in more detail in later sections.
Value Types vs Reference Types
C# variables can be categorized into two main types:
- Value types: These include simple types like
int
,float
,bool
, andstruct
. They will always be initialized with a default value - e.g.int
will be initialized with0
,bool
asfalse
, etc. - Reference types: These include
class
,interface
,delegate
, and arrays. These are typically nullable by default.
The main difference is how they are stored in memory and how they are passed to methods.
We'll dive deeper into different data types and how to work with them in C# in the types section.