C# has a rich type system, which is divided into two main categories:
- Value types
- Reference types
1. Value types:
Value types store data directly in the memory allocated to the variable. Some common value types include:
- Integral types:
sbyte
: 8-bit signed integer.byte
: 8-bit unsigned integer.short
: 16-bit signed integer.ushort
: 16-bit unsigned integer.int
: 32-bit signed integer(most common). uint
: 32-bit unsigned integer.long
: 64-bit signed integer.ulong
: 64-bit unsigned integer.Floating-point types:
float
: 32-bit single-precision floating-point number.double
: 64-bit double-precision floating-pointnumber (most common). decimal
: 128-bit decimal number, suitable for financial calculations.Other types:
bool
: logical value (true or false).char
: a single Unicode character.enum
: enumeration type, defines a set of named constants.struct
: structure type, allows grouping variables of different data types.
2. Reference types:
Reference types store the memory address of the data, not the data itself. Reference type variables point to the location where the data is stored on the heap. Some common reference types:
string
: a sequence of characters.object
: the base type of all other data types in C#.class
: class type, allows creating objects with properties and methods.interface
: defines a set of methods that a class must implement.delegate
: a pointer to a method.array
: stores a collection of elements of the same type.
Summary of some C# data types:
Data Type | Description | Range of Values |
---|---|---|
int | 32-bit integer | -2,147,483,648 to 2,147,483,647 |
double | 64-bit floating-point number | ±5.0 × 10<sup>−324</sup> to ±1.7 × 10<sup>308</sup> |
decimal | 128-bit decimal number | (-7.9 x 10<sup>28</sup> to 7.9 x 10<sup>28</sup>) / 10<sup>0 to 28</sup> |
char | Unicode character | U+0000 to U+ffff |
bool | Boolean value | true or false |
string | String of characters |
- When declaring a variable, you need to specify the data type for that variable. For example:
int age = 25;
- C# provides the
checked
andunchecked
keywords to control integer overflow. - The
dynamic
data type allows you to bypass compile-time type checking.
Understanding data types in C# is crucial for writing efficient code and avoiding errors.
0 Comments
Post a Comment