Part 2: C# Fundamentals: Variables and Data Types
In this lesson, we’ll explore the fundamental concepts of variables and data types in C#. These two elements are essential for storing and handling information in your programs.
What is a Variable?
Variables are like containers that we use to store data in our programs. For example, if you want to store a person’s age, you can save it in a variable called age
. Variables allow our programs to “remember” information while they run.
To declare a variable in C#, we follow this format:
type variableName = value;
Where:
- type: defines the kind of data the variable will store.
- variableName: is the name you give the variable.
- value: is the data you want to store in the variable.
Example:
int age = 28; string name = "Peter"; double temperature = 21.5;
In this case, we’ve declared a variable age
of type int
, a variable name
of type string
, and a variable temperature
of type double
.
Naming Conventions: Camel Case
In C#, it’s good practice to follow certain naming conventions to improve code readability. For naming variables, we generally use camelCase, where the variable name starts in lowercase and each new word begins with a capital letter, like myName
or dateOfBirth
.
Example of variables named in camelCase:
int numberOfStudents = 18; string fullName = "Paul Garcia"; double productPrice = 29.99;
These conventions make the code more readable and easier to understand, especially when working in a team.
Data Types in C#
In C#, there are several basic data types you can use to define the kind of information each variable will store:
- int: for whole numbers, like
8
,105
, or-20
. - double: for decimal numbers, like
4.8
,3.1416
, or-7.28
. - string: for text, like
"Hi Codu"
,"C# is the best"
. - bool: for true/false values (
true
orfalse
).
When to Use Each Data Type
- int: Use
int
when you need to work with whole numbers (without decimals). It’s common in situations where you don’t need decimal values, like counting people or iterations in a loop. - double: Opt for
double
when you need to work with decimals, like in money calculations, temperatures, or percentages. - string: Use
string
whenever you’re working with text. It’s useful for names, addresses, messages, and any other textual data. - bool: Use
bool
for true or false values, ideal for conditions (for example, whether a user is logged in or not).
Type Conversion
In C#, sometimes you need to convert data from one type to another. There are two types of conversions:
Implicit Conversion: This happens automatically when there’s no loss of information. For example, you can convert an
int
todouble
without issues, asdouble
can contain whole numbers.int wholeNumber = 10; double decimalNumber = wholeNumber; // Implicit conversion from int to double
Explicit Conversion: You need to tell C# to perform the conversion because information might be lost. This is done using a “cast”:
double decimalValue = 9.8; int integerValue = (int)decimalValue; // Explicit conversion from double to int
Here,
integerValue
will be9
, as the decimal portion is lost when converting toint
.
You can also convert data using specific methods, like ToString()
to convert to text or Parse()
to transform text into a number.
int number = 42; string text = number.ToString(); // Convert from int to string string numberAsText = "123"; int convertedNumber = int.Parse(numberAsText); // Convert from string to int
Another example is converting bool
to string
:
bool isActive = true; string status = isActive.ToString(); // Result: "True"
Practical Example: Average Calculator
Let’s look at a practical example where we’ll use variables, data types, and conversions. We’ll create an average calculator that takes three numbers and calculates their average.
using System; class AverageCalculator { static void Main(string[] args) { Console.WriteLine("Enter the first number:"); double number1 = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Enter the second number:"); double number2 = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Enter the third number:"); double number3 = Convert.ToDouble(Console.ReadLine()); double average = (number1 + number2 + number3) / 3; Console.WriteLine("The average is: " + average); } }
This program prompts for three numbers, calculates their average, and displays it on the screen.
Practice Exercises
Create a Text Variable: Declare a variable
name
of typestring
and assign it your name. Print a message saying "Hi, [name]".Store a Person’s Data: Create variables to store a person’s name, age, and body temperature (using
string
,int
, anddouble
). Then, print a message like: "My name is [name], I am [age] years old and my temperature is [temperature]°C".Type Conversion: Create a
double
variable with the value6.9
. Convert this value toint
and display both values on the screen to see the difference.