In C#, data types are used to define the type and size of data that can be stored in variables. Here are some commonly used data types in C# along with code examples and explanations:
1. Numeric Types:
v `int`:
Represents signed integers with a range of -2,147,483,648 to 2,147,483,647.
int age = 25;
v `double`:
Represents double-precision floating-point numbers.
double pi = 3.14159;
v `decimal`:
Represents decimal numbers with higher precision for financial and monetary
calculations.
decimal salary = 5000.50m;
2. Boolean Type:
v `bool`:
Represents a Boolean value that can be either `true` or `false`.
bool isRaining = true;
3. Character Type:
v `char`:
Represents a single character and is enclosed in single quotes.
char grade = 'A';
4. String Type:
v `string`:
Represents a sequence of characters and is enclosed in double quotes.
string name = "John";
5. Array Types:
v `int[]`:
Represents an array of integers.
int[] numbers = { 1, 2, 3, 4, 5 };
v `string[]`:
Represents an array of strings.
string[] fruits = { "Apple",
"Banana", "Orange" };
6. Other Types:
v `DateTime`:
Represents a date and time value.
DateTime now = DateTime.Now;
v `object`:
Represents a base type from which all other types are derived.
object obj = 42;
v `var`:
Implicitly determines the type of the variable based on the assigned value.
var price = 9.99;
These
are just a few examples of data types in C#. Each data type has its own range,
size, and purpose, which you can choose based on the requirements of your
program. By utilizing appropriate data types, you ensure type safety and
efficient memory usage in your C# code.
0 Comments