Home » C# Data Types : A Tutorial

C# Data Types : A Tutorial

by wskandot71

In C#, data types define the kind of data a variable can store. Choosing the correct data type is crucial for memory efficiency, performance, and accuracy.

This tutorial will cover:

  • Categories of Data Types
  • Value Types vs Reference Types
  • Common Data Types with Examples
  • Implicit and Explicit Type Conversion
  • Nullable Types
  • Using var for Type Inference
  • Best Practices

1. Categories of Data Types in C#

C# data types are classified into:

  1. Value Types: Store data directly in memory.
  2. Reference Types: Store references (memory addresses) rather than actual data.
  3. Pointer Types: Used in unsafe code for direct memory manipulation.

2. Value Types

Value types store data directly and are stored in the stack memory.

Common Value Types

Data Type Size Example Description
int 4 bytes int age = 30; Stores whole numbers
double 8 bytes double price = 9.99; Stores decimal numbers
float 4 bytes float rate = 5.5f; Stores floating-point numbers
decimal 16 bytes decimal salary = 10000.50m; Used for financial calculations
char 2 bytes char letter = ‘A’; Stores a single character
bool 1 byte bool isActive = true; Stores true or false
byte 1 byte byte data = 255; Stores values from 0 to 255
short 2 bytes short num = 32000; Stores values from -32,768 to 32,767
long 8 bytes long population = 8000000000; Stores large whole numbers

Example of Value Types

int number = 100;
double temperature = 36.6;
char grade = 'A';
bool isPassed = true;

3. Reference Types

Reference types store the memory address where the actual data is located, rather than the data itself. They are stored in the heap.

Common Reference Types

Data Type Example Description
string string name = “John”; Stores text
object object obj = 25; Can store any data type
dynamic dynamic value = “Hello”; Type determined at runtime
class Person p = new Person(); Custom data structures
interface interface IShape {} Defines contract for classes

Example of Reference Types

string message = "Welcome to C#";
object obj = 42; // Can hold any data type
dynamic value = 3.14; // Type decided at runtime

4. Implicit and Explicit Type Conversion

Type conversion allows converting one data type to another.

Implicit Conversion (Automatic)

C# automatically converts smaller data types to larger types.

int num = 100;
double largeNum = num; // Implicit conversion
Console.WriteLine(largeNum); // Output: 100.0

Explicit Conversion (Casting)

Larger types must be manually converted into smaller types.

double pi = 3.14159;
int roundedValue = (int)pi; // Explicit conversion (casting)
Console.WriteLine(roundedValue); // Output: 3

Using Convert Class

C# provides Convert methods to handle conversions.

string str = "123";
int num = Convert.ToInt32(str); // Converts string to int
Console.WriteLine(num); // Output: 123

5. Nullable Types

C# allows nullable value types using ?, which means a variable can store either a value or null.

Example:

int? age = null; // Can hold an integer or null
double? temperature = 36.6;

Checking for Null Values

if (age.HasValue) {
    Console.WriteLine("Age: " + age.Value);
} else {
    Console.WriteLine("Age not assigned");
}

Using Null Coalescing Operator (??)

If the variable is null, a default value is assigned.

int result = age ?? 18; // If 'age' is null, assign 18

6. Using var for Type Inference

C# allows type inference using var, meaning the compiler determines the type.

Example:

var x = 100; // Inferred as int
var name = "Alice"; // Inferred as string

Rules for Using var:

  • The variable must be initialized at declaration.
  • Cannot be null unless explicitly assigned a nullable type.
  • Improves readability but should be used carefully.

7. Best Practices for Using Data Types

Use the smallest data type required

byte age = 25; // Good (smallest required)
int age = 25; // Acceptable but not optimal

Use decimal for financial calculations

decimal salary = 50000.75m;

Prefer string over char[] for text storage

string greeting = "Hello"; // Better
char[] letters = { 'H', 'e', 'l', 'l', 'o' }; // Avoid

Use nullable types for optional values

int? discount = null; // Good for optional fields

Use var only when necessary

var price = 99.99; // Acceptable
double price = 99.99; // Better for clarity

Conclusion

  • Value Types store data directly in the stack memory.
  • Reference Types store memory addresses (heap memory).
  • Implicit and Explicit Conversion is needed for type compatibility.
  • Nullable Types (int?, double?) allow null values.
  • Type Inference (var) simplifies code but should be used carefully.
  • Choosing the right data type optimizes performance and memory usage.

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.