Software Development

Working with C# Data Types


Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

C# tutorials

Data types in C# are basic programming concepts that define what type of data a variable can hold. C# is a statistically-typed language, and, as such, every variable has to be declared with a specific data type prior to being used. In this programming tutorial, we will discuss the different data types that C# has to offer, including the built-in data types and reference types. We will also cover the concept of type conversion and showcase some code examples showing their usage.

Jump to:

What are Data Types in C#?

As noted in our introduction, data types denote the type of information a variable can hold, such as a string or numeric value. Further, they also define the range of values the variable can hold and the types of operations that can be performed on the variable. For instance, you would not perform calculations on a text value, nor would you capitalize a number.

C# data types are roughly classified into two main categories: value types and reference types

. We will discuss each of these data types in the sections below. But first, let’s discuss the benefits of using data types in our C# programs.

Read: JetBrains ReSharper IDE Review

Benefits of Using Data Types

Aside from being a necessary element to any application a developer builds, data types also offer the following benefits:

  • Enhances memory efficiency: By allocating the proper memory for variables based upon their data type, we make our memory usage more efficient, resulting in better performance
  • Type safety: Using data types enables programmers to catch type-related errors at compile-time versus runtime
  • Better code clarity: Defining our data types helps clarify their intended use and purpose, mitigating the chances of misuse.

Now that we understand some of the core benefits of using C# data types, we can discuss the different types available to use.

Built-in C# Data Types

C# has several forms of built-in types, including:

  • Numeric types
  • Character types
  • Boolean types
  • Integer types
  • Structs

Numeric Types in C#

C# offers a variety of numeric types. They include:

  • byte and sbyte: Used for 8-bit signed and unsigned integers.
  • short and ushort: Used for 16-bit signed and unsigned integers
  • int and uint: Used for 32-bit signed and unsigned integers. Holds values from -2,147,483,648 to 2,147,483,647.
  • long and ulong: Used for 64-bit signed and unsigned integers. Holds values from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,808
  • float: Used for 32-bit floating-point numbers. Holds values up to 7 decimals.
  • double: Used for 64-bit double-precision floating-point numbers. Holds values up to 15 decimals.
  • decimal: 128-bit decimal floating-point numbers

For starters, integer data types are used to represent whole numbers. There are several types of integers, including byte, short, int,, and long. Each type of integer holds a certain type of numeric value, shown in our list above. To define a basic int and assign it a value, we use the following syntax:

int age = 20;

If we wanted to create a long and assign it a value, we could use the following code example:

long earthAge = 400000000L;

Floating-point types, meanwhile, represent numbers with decimal points or that are fractional. Floating point types include float, double, and decimal. If we wanted to create a floating point type of float, we could do so in the following manner

:
float myHeight = 6.5F;

Character and String Types in C#

For single unicode characters, C# relies on the char. The syntax to declare a char variable can be seen in the following code example:

char test;

To assign a value to a char, simply enclose the value in quotation marks, as shown below:

char test = ‘A’;

If you want to create a variable capable of holding more than a single unicode character, you will want to create a string type. string types can hold anywhere from 1 to a billion characters. They are typically used to hold words, sentences, or even paragraphs of text-based data. Here is the syntax for creating a string in C#:

string name =”Nicholas”;

You can also create a string using the System.String class. The syntax is slightly different – you have to use an uppercase String versus the lowercase version:

String name2 = “Nick”;

Which you choose to use is up to the programmer – neither choice is wrong. We will discuss strings in greater detail in an upcoming tutorial.

Read: Rider IDE Review

Boolean Types

The bool type is used to represent a boolean value, either true or false in C# . They are commonly used when you need to perform an action depending upon whether one statement or another is true or false.

For example, let’s say we want to figure out if one number is greater than another. We can do so using a bool expression. First, we create two integers, then use Console.WriteLine to print the result of our evaluation to the screen. Here is some sample code demonstrating this:

int age1 = 20;
int age2 = 50;
Console.Writeline(age1 > age2); //returns False because ag1 IS NOT greater than age 2

In this example, we assign the age1 variable a value of 20 and our age2 variable the value of 50. We then ask if age1 is greater than age2. Since it is not, our bool expression will return a false value.

Integer Data Types and Floating Point Types

We briefly viewed the integer and floating point types in our list of the different numeric types. Here, we discuss them in greater detail. For starters, integer data types are used to represent whole numbers. There are several types of integers, including byte, short, int,, and long.

Enumerations and Enums

In C#, enum defines named constants, which are values that cannot be changed or that are read-only. Developers use constant when they intend for their data to never change and remain consistent. Enum values are in a list format and begin with the first entry starting at value 0 by default. The second item in the list would be value 1, and so forth. For example, let’s say you have an enum that holds the days of week. You would define it in this manner:

enum Days { 
Sunday, //  index 0
Monday, // index 1
Tuesday, // index 2
Wednesday, index 3
Thursday, index 4
Friday, index 5
Saturday index 6
}

Once the values are assigned to an Enum, we can then assign the individual values to a variable. To do so, we would use code similar to the following:

Days today = Days.Monday;
Console.WriteLine(today);

This would print “Monday” to the screen.

Structs

Structs can be thought of as data structures that groups data. They are similar to classes but are value types that can hold constructors, constants, fields, methods, operators, indexers, and more. They are useful if you need a structure to hold data values that do not rely on inheritance, such as key-value pairs. For example, let’s say we wanted to hold the location of a building based on its longitude and latitude. We could do so in a Struct in the following manner:

struct Location
{
    public int x;
    public int y;
}

Reference Types in C#

References types store a “reference” to actual data versus the actual value itself. The reference stores the address where a value is stored, which can be thought of as a pointer to a memory location. References types are able to store references to classes, strings, arrays, and delegates
Reference types store references to the actual data on the heap. They include classes, strings, arrays, and delegates.

Type Conversion in C#

There are two forms of type conversion in C#: implicit and explicit. Implicit type conversion lets you automatically convert from compatible data types, such as converting an int value to a long. Explicit type conversion is needed when you want to convert incompatible data types.

For example, let’s say we want to pass a smaller value to a value type that holds a larger value. In our example below, we will use implicit type conversion (or casting) to pass an int to a double:

int myWeight = 200;
double myDoubleWeight = myWeight;

Since both data types are compatible, the conversion from int to double is automatic and we do not need to write any further code to force the conversion.

However, if we wanted to perform the reverse operation and assign a double to an int, we would need to manual cast the value, as an int does not accept decimal values. When this conversion happens, the numbers after the decimal point are removed and the floating point value becomes an integer value or whole number instead. Here is how that looks in code:

double myDoubleWeight = 200.58;
int myWeight = (int) myDoubleWeight;
Console.WriteLine(myDoubleWeight);
Console.WriteLine(myWeight);

Notice how we place (int) before myDoubleWeight. This code is where we force the conversion from a double to an int. If we run this program, we get the following output:

200.58
200

Final Thoughts on C# Data Types

Understanding the different data types and how they work is crucial for creating efficient and error-free C# applications. This programming tutorial covered the basic built-in data types C# has to offer, as well as its reference types. We also discussed both implicit and explicit type conversions and type casting.

Read: Best Tools for Remote Developers