C# Data Types: Choosing the Right One with Best Practices

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?

  • Use int for most numbers.
  • Use long for large numbers.
  • Use byte if the value is between 0-255 (e.g., colors, file sizes).

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?

  • Use float for light precision (e.g., game physics).
  • Use double for scientific calculations.
  • Use decimal for money calculations (e.g., currency).

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?

  • Use bool for conditions (e.g., if statements).

Example: Boolean Usage

bool isSunny = false;
Console.WriteLine("Is it sunny? " + isSunny);        

4. Character Type (Single Letter)

Stores a single character.


When to use?

  • Use char for single characters (e.g., grades, keyboard inputs).

Example: Char Usage

char firstLetter = 'J';
Console.WriteLine("First letter: " + firstLetter)        

5. String Type (Text)

Stores a sequence of characters.

When to use?

  • Use string for words, sentences, and any text data.

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?

  • Use object when you don’t know the exact data type.

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? ??


要查看或添加评论,请登录

Divya Soni的更多文章

社区洞察

其他会员也浏览了