C# Data Types
Value Types
Value types are built-in data types that store values directly in their memory locations. Value types include:
- Integer types: These types store whole numbers, such as 1, -2, or 1000. Examples of integer types are byte, sbyte, short, ushort, int, uint, long, and ulong.
Example:
int age = 30;
- Floating-point types: These types store numbers with fractional parts, such as 3.14159 or -0.5. Examples of floating-point types are float and double.
Example:
double pi = 3.14159;
- Character type: This type stores a single character, such as 'A', 'b', or '$'. The char data type is used to represent individual characters.
Example:
char letter = 'A';
- Boolean type: This type stores a logical value, either true or false. The bool data type is used to represent binary values.
Example:
bool isStudent = true;
Reference Types
Reference types are built-in data types that store references to memory locations. Reference types include:
- Object type: This type represents an instance of a class. The object data type is the base type for all other reference types.
Example:
Person person = new Person();
- String type: This type represents a sequence of characters. The string data type is used to represent text.
Example:
string name = "John Doe";
- Array type: This type represents a collection of elements of the same type. Arrays store multiple values of the same data type.
Example:
int[] numbers = new int[5];
Nullable Types
Nullable types are value types that can also have a null value. Nullable types are represented using the ? suffix after the data type. For example, int? represents a nullable integer, and bool? represents a nullable boolean.
Example:
int? age = null;
User-Defined Types
User-defined types are types that are defined by the programmer. These include:
- Structures: Structures are similar to classes, but they cannot inherit from other classes and they are used to group related data together.
Example:
struct Point
{
public int x;
public int y;
}
- Enumerations: Enumerations are user-defined types that consist of a set of named constants.
Example:
enum DayOfWeek
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}