Skip to main content

Data Types

Introduction to Data Types in C#

In C#, a data type defines the type of a variable. Whether it can be a number, a letter, a word, a sentence, or a boolean (true or false), everything is determined by its data type. The C# programming language is strongly typed, which means every variable and constant has a type, as does every expression that evaluates to a value.

C# provides several built-in data types, but we'll focus on the most commonly used ones.

Numeric Data Types

Numeric data types hold numeric values. They can be further divided into two types: Integer types and Floating-point types.

Integer Types

Integer types can hold whole numbers. C# offers several variations of integers:

  • int: used for whole numbers.
  • byte: used for small numbers.
  • long: used for bigger numbers.
int myInt = 10;
byte myByte = 20;
long myLong = 3000;

Floating-Point Types

Floating-point types can hold numbers with fractional parts. C# offers two floating-point types:

  • float: used for numbers with small decimal points.
  • double: used for numbers with large decimal points.
float myFloat = 10.2f;
double myDouble = 20.3456;

Boolean Data Type

The boolean data type bool represents two values: true and false.

bool isCSharpFun = true;
bool isFishTasty = false;

Character and String Data Types

Character Type

The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c'.

char myLetter = 'D';

String Type

The string data type is used to store a sequence of characters (text). String values must be surrounded by double quotes.

string myText = "Hello World";

Null Data Type

The null keyword is a special case in C#. It's a literal that represents a null reference, one that does not refer to any object.

string myString = null;

Conclusion

Understanding data types is a fundamental part of learning C#. It allows you to define what type of data can be stored and manipulated within your program. In this article, we've covered the most commonly used data types, but remember, C# offers even more. As you gain experience, you'll find yourself using a wider variety of data types.