C# data types

www.ig‮c.aeditfi‬om

In C#, variables can be declared with a data type, which determines the kind of values that can be stored in the variable. C# has several built-in data types, as well as the ability to create custom data types through classes and structs.

Here are some of the most common data types in C#:

Numeric Types

Integer Types

C# provides several integer types, which are used to store whole numbers without a fractional component. These types can be signed (positive or negative) or unsigned (positive only).

  • sbyte: 8-bit signed integer (-128 to 127)
  • byte: 8-bit unsigned integer (0 to 255)
  • short: 16-bit signed integer (-32,768 to 32,767)
  • ushort: 16-bit unsigned integer (0 to 65,535)
  • int: 32-bit signed integer (-2,147,483,648 to 2,147,483,647)
  • uint: 32-bit unsigned integer (0 to 4,294,967,295)
  • long: 64-bit signed integer (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
  • ulong: 64-bit unsigned integer (0 to 18,446,744,073,709,551,615)

Floating-Point Types

C# provides two floating-point types, which are used to store numbers with a fractional component:

  • float: 32-bit floating-point number (approximately ±1.5 x 10^-45 to ±3.4 x 10^38 with 7 significant digits)
  • double: 64-bit floating-point number (approximately ±5.0 x 10^-324 to ±1.7 x 10^308 with 15-16 significant digits)

Decimal Type

The decimal type is used to store decimal numbers with a high degree of precision and is often used in financial applications:

  • decimal: 128-bit decimal number (-10^28 +1 to 10^28 -1 with 28-29 significant digits)

Boolean Type

The bool type is used to store a logical value that can be either true or false.

Character Type

The char type is used to store a single character:

  • char: 16-bit Unicode character (0 to 65535)

String Type

The string type is used to store a sequence of characters:

  • string: sequence of Unicode characters

Object Type

The object type is the base class for all types in C#, and can store any kind of value:

  • object: any type (value types, reference types, arrays, and interfaces)

Note that in C#, variables can also be declared using the var keyword, which allows the compiler to infer the data type based on the value assigned to the variable. For example:

var age = 30; // age is inferred as an int
var name = "John"; // name is inferred as a string