If you’re a regular reader of the SubMain blog, you’ll know that we often publish posts about fundamental concepts of the C# language. Today’s post adds yet another chapter to this ongoing series. The topic we’ll cover is, in fact, as fundamental as it can get: C# data types.
As the title suggests, this post will cover the three most common C# data types. For each one of the types, we’ll start out by offering some justification on why the type deserves to be on the list. Then, we’ll proceed to show you some interesting facts you need to know about the type. When relevant, you’ll also see some code examples.
But before we start, there are two questions that need answering. First, what is our definition of a C# data type? And what does it actually mean for a type to be “common”?
C# Data Types: A Loose Definition
Well, the line between .NET and C# is a little blurry, especially for beginners. People tend to use the two terms somewhat interchangeably. Because of that, for the purposes of this article, we define “C# type” very loosely.
Sure, all of the types we’ll cover happen to be fundamental C# types. All of them have a keyword in the language and get special treatment built into the CLR. But this is mostly a coincidence. Even if such types didn’t have this special status in the framework, we still would’ve called them C# data types, just because that’s what they’re called by a reasonable portion of developers.
Common Types?
With that out of the way, let’s address the word “common.” What do we mean by a common type?
For our purposes, consider common to mean
- fundamental, and
- widely used.
All of the types we’ll cover today meet these criteria. They are all fundamental, which means they’re building blocks of more complex types and concepts. For that reason, they’re probably the most used types, and they’re one of the first that novice developers encounter.
Most Common C# Data Types: Let’s Get to Them
Now you know what we mean by “common types.” So, it’s time to finally meet them!
The types we’ll cover are, in order, string, int, and bool. Let’s get started.
String
Most useful programs will have some kind of output. They will, at some time, display/log/print information in textual format. Also, think about all of the RESTful APIs out there that send and receive data in textual format, nowadays more commonly in JSON, but also in XML or other formats.
So, I think you’ll agree that the string type rightfully deserves a place on our list. With that out of the way, let’s examine some properties of the C# string.
A string is a String is a System.String
What are the characteristics of the C# string? First of all, string (all lowercase) is a C# keyword. It works as an alias for the System.String type in the .NET base class library (BCL).
So, here’s the answer to one of the most asked questions about the type. What’s the difference between string and String (or System.String)? None.
The String Doesn’t Change
A very important property of the string type in C# is its immutability. In other words, a string can never change once it’s initialized?at least in normal, everyday use. Our article about functional programming in C# mentions the implications and benefits of using immutable types. Consider checking it out after you’re done with today’s post.
For now, keep in mind that all methods that appear to change the string are, in fact, creating a new one. So you must always assign the method’s return to a variable; otherwise, your code won’t work as expected. Consider the following example:
string s = "26/05/1967"; s.Replace("/", "-"); Console.WriteLine(s); // prints "26/05/1967" string s = "26/05/1967"; s = s.Replace("/", "-"); Console.WriteLine(s); // prints "26-05-1967"
The first excerpt shows a common mistake that happens when the developer doesn’t know that the string is immutable and thinks that the replacement actually changes the instance. The second code excerpt shows the correct way to use the Replace method by assigning its result to the variable.
No String Is Like the Other
If this whole string immutability thing is new for you, you might be wondering whether it can cause performance issues. The short answer for that is, “Yeah, of course.”
There are scenarios in which the misuse of strings can lead to performance problems due to their immutable nature. There are ways to counter that, fortunately. For instance, there’s a class called StringBuilder, which can be used to concatenate a large number of string instances in situations where the performance would suffer.
Another cool strategy for mitigating potential performance issues is the technique called “String Interning.” If you create the same string 1000 times, interning will see that only one occurrence of the string is created in the memory. That avoids unnecessary memory allocation and makes comparisons easier since if two strings are interned, they’d only need to be compared via their references instead of their contents.
Int
When it comes to numbers, C#/.NET offers a huge variety for you to choose from. Which one should you pick? It all comes down to basically two things:
- the nature of the information or concept you’re trying to express
- the range (i.e., the minimum and maximum possible value) the concept you’re trying to express can reach
C# provides several options of types you can use to express some concept using integer numbers. Sure, int is the one that people know the most, but there’s also byte (and its signed counterpart sbyte), short and long, along (no pun intended) with their unsigned counterparts, ushort and ulong. Finally, int also has its unsigned counterpart, uint.
An int, By Other Name, Would Smell Just As Sweet
This is another common question/misconception about C# types. Many beginner developers wonder about the difference between int and System.Int32. As in the string case, the answer is none. All-lowercase int is a C# keyword that works as an alias for the System.Int32 type that .NET provides. So, the following two lines are equivalent:
int x = 10; System.Int32 x = 10;
Int Can’t Be Null
The int type is a value type. In C#/NET, when you create a variable of a value type, the content of the variable is the value itself. That’s in contrast to it being a reference that points to an object, as is the case with reference types.
Since you can think of null as a reference that points to nowhere, int can’t be null because it doesn’t store references. Rather, it stores the value itself. There’s a way to counter this limitation, which is to employ nullable types.
Int Has a Long Range…But Not Longer Than Long
As you’ve just seen, the int keyword is nothing but an alias to System.Int32. That 32 means that the value of an int stored used 32 bits. That results in 2^32 possible values that can be expressed. That’s 4294967296 possible numbers.
Finally, keep in mind that our friend int is a signed type, which means it can express negative numbers. That means that instead of going from 1 to 4294967296 (or 0 to 4294967295), the actual range of numbers expressable by the int type goes from -2,147,483,648 to 2,147,483,647. When writing code, you can easily access the minimum and maximum possible values for int using the MinValue and MaxValue properties:
Console.WriteLine(int.MinValue); // prints -2147483648 Console.WriteLine(int.MaxValue); // prints 2147483647
If such a range isn’t enough for your application, you should consider using the long type, which is a signed 64-bit integer. As such, long has a range going from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
If that range doesn’t suffice, though, the solution for your problems is the BigInteger structure that resides in the System.Numerics namespace from the .NET BCL.
Bool
Did you watch something on Netflix yesterday? Do you drink coffee every day? Each one of these questions has a yes or no answer. It’s either true that you’re older than 25 or it’s false. The same goes for the other questions.
In order to model concepts or pieces of information like the ones above, you should use the C# data type called bool.
By Now, You Know the Drill: bool Is an Alias
At this point, you’re familiar with the pattern. The following two lines are equivalent:
bool b = false; System.Boolean = false;
It’s Either True or False, But It’s Not Null
Since bool is also a value type, it can’t be null. But as you’ve seen with int, there’s a way to counter that: by using nullable types. In the following examples, the four lines inside the Main method are equivalent:
using System; class MainClass { public static void Main (string[] args) { Nullable<bool> b = false; Nullable<Boolean> c = false; bool? d = false; Boolean? e = false; } }
Learning a Programming Language Might Be a Challenge…But It Doesn’t Have to Be a Burden
The C# language and the .NET framework offer a huge variety of data types to allow you to model any concept or idea. Today’s post focused on three of them: the string, int, and bool types.?An honorable mention goes to our old friend DateTime. While it’s not fundamental in the same sense as the types covered today?it’s not one of the simplest types that get special treatment in the framework and a C# shorthand?it’s definitely fundamental in the sense that it’s one of the most used types.
There are many more types and concepts you need to be aware of to be a proficient C# developer. Here on the SubMain blog, we have already covered many of them and will continue to do so. We hope our content can make the challenge of learning this language easier for you. Thanks for reading. See you next time!
Learn more how CodeIt.Right can help you automate code reviews and improve the quality of your code.
1 Comment. Leave new
[…] The 3 Most Common C# Data Types: Explanations and Examples – Carlos Schults […]