Welcome to the section on Data Types in C#. Understanding data types is fundamental to programming in any language, as they define the kind of values that can be stored and manipulated. In this tutorial, we will explore various data types available in C#, including both primitive (or value) types and reference types.
Data types determine the range of values a variable can hold and the operations that can be performed on it. C# is a statically typed language, meaning that the type of a variable must be known at compile time. This helps catch errors early in the development process.
Primitive data types are the basic building blocks for all other data types in C#. They include:
Integer Types: Used to store whole numbers.
int: Represents 32-bit signed integers.long: Represents 64-bit signed integers.short: Represents 16-bit signed integers.byte: Represents 8-bit unsigned integers.Floating-Point Types: Used to store decimal numbers.
float: Represents single-precision floating-point numbers.double: Represents double-precision floating-point numbers.Decimal Type: Used for high precision calculations, such as financial computations.
decimal: Represents 128-bit signed integers with a fixed scale and precision of up to 28-29 digits.Character Types: Used to store individual characters.
char: Represents a single Unicode character.Boolean Type: Used to store true or false values.
bool: Represents Boolean values (true or false).Reference data types refer to objects and are stored on the heap. They include:
Let's dive into some practical examples to illustrate these data types in action.
CodeBlock language="csharp">
{`int number = 10;
long bigNumber = 123456789012345;
short smallNumber = -32768;
byte unsignedByte = 255;`}
</CodeBlock>
<Tip variant="info">Note that `byte` is the only unsigned integer type in C#.</Tip>
### Floating-Point Types
```csharp
CodeBlock language="csharp">
{`float pi = 3.14f;
double precisePi = 3.141592653589793;`}
</CodeBlock>
<Tip variant="info">The `f` suffix is used to denote a float literal.</Tip>
### Decimal Type
```csharp
CodeBlock language="csharp">
{`decimal highPrecisionNumber = 0.1m + 0.2m;
Console.WriteLine(highPrecisionNumber == 0.3m); // True`}
</CodeBlock>
<Tip variant="info">The `m` suffix is used to denote a decimal literal.</Tip>
### Character and Boolean Types
```csharp
CodeBlock language="csharp">
{`char letter = 'A';
bool condition = true;`}
</CodeBlock>
### String Type
```csharp
CodeBlock language="csharp">
{`string greeting = "Hello, World!";
Console.WriteLine(greeting.Length); // Outputs 13`}
</CodeBlock>
## What's Next?
In the next section, we will explore operators in C#, which are used to perform operations on variables and values. Understanding operators is crucial for performing arithmetic calculations, comparisons, and more.
Stay tuned!