C# Data Types: Choosing the Right One with Best Practices
In C#, data types define what kind of data a variable can store. Choosing the right data type is important for memory usage and performance.
Let’s explore the main data types in C# with simple examples and when to use them.
1. Integer Types (Whole Numbers)
Used for storing numbers without decimals.
When to use?
Example: Integer Usage
int apples = 5;
long population = 7800000000;
byte age = 30;
Console.WriteLine("Apples: " + apples);
2. Floating-Point Types (Decimal Numbers)
Used for storing numbers with decimals.
When to use?
Example: Floating-Point Usage
float weight = 65.5f;
double distance = 12345.6789;
decimal price = 199.99m;
Console.WriteLine("Weight: " + weight);
3. Boolean Type (True or False)
Stores only two values: true or false.
When to use?
Example: Boolean Usage
bool isSunny = false;
Console.WriteLine("Is it sunny? " + isSunny);
4. Character Type (Single Letter)
Stores a single character.
领英推荐
When to use?
Example: Char Usage
char firstLetter = 'J';
Console.WriteLine("First letter: " + firstLetter)
5. String Type (Text)
Stores a sequence of characters.
When to use?
Example: String Usage
string greeting = "Hello, World!";
Console.WriteLine(greeting);
6. Object Type (Any Data)
object can store any type of data.
When to use?
Example: Object Usage
object data = 42;
Console.WriteLine("Data: " + data);
7. Nullable Types
A normal int cannot store null, but int? can.
Example:
int? age = null;
Console.WriteLine("Age: " + (age ?? 0)); // Output: 0 if null
Summary
Want me to expand on any topic? ??