What Are Data Types in C#: Explanation and Examples
data types define the kind of data a variable can hold, such as numbers, text, or true/false values. They help the computer understand how to store and use the data correctly.How It Works
Think of data types in C# like different containers for storing things. Just like you wouldn't put water in a shoe box, you use the right data type to store the right kind of information. For example, numbers go into int or double containers, while words go into string containers.
Each data type tells the computer how much space to reserve and what operations can be done on the data. This helps avoid mistakes, like trying to add a number to a word without meaning.
Example
This example shows how to declare variables with different data types and print their values.
using System; class Program { static void Main() { int age = 30; // whole number double price = 19.99; // decimal number string name = "Alice"; // text bool isStudent = true; // true or false Console.WriteLine($"Name: {name}"); Console.WriteLine($"Age: {age}"); Console.WriteLine($"Price: {price}"); Console.WriteLine($"Is student: {isStudent}"); } }
When to Use
Use data types whenever you want to store information in your program. Choosing the right data type helps your program run faster and use memory wisely. For example, use int for counting items, double for prices or measurements, string for names or messages, and bool for yes/no or true/false decisions.
In real life, if you are making a program for a store, you would use numbers to track stock, text for product names, and true/false to check if an item is on sale.
Key Points
- Data types tell the computer what kind of data is stored.
- C# has many built-in data types like
int,double,string, andbool. - Choosing the right data type helps avoid errors and improves performance.
- Variables must be declared with a data type before use.