C# has a lot of data types and some aren’t even used. We often use them without really knowing why we use them and what the data types are capable of. In the series “The C# data types”, I show you a few of those data types and look into them. Some basic examples, tips, and tricks. In this article: what is an int?
What is an int?
An int is declared by using the int data type, followed by the name of the variable. An int has a default value of 0 (zero).
An int (integer) can only contain whole numbers, so no decimals. The highest number an int can have is 2,147,483,647 and the lowest is -2,147,483,647. If you need a higher number you can use the long.
The System.Int32 and int are the same, where int is an alias of the System.Int32.
You can use integers to perform some calculations, like the example below.
int firstNumber = 4;
int secondNumber = 9;
int outcome = firstNumber + secondNumber; // Gives 13
Integers are not only used to calculate but they can also be used in enums and identifiers (IDs).
// Enum with identifiers
public enum Course
{
Unknown = 0,
Starter = 1,
Main = 2,
Desert = 3
}
// Enum without identifiers, numbers are still the same
public enum Course
{
Unknown,
Starter,
Main,
Desert
}
Parsing
There are several ways of parsing the int, meaning you can change the type of a string to an int, for example. You can only do this when the string contains numbers. If it contains a letter it will throw an exception. Below are the most common ways to parse an int.
int.Parse()
string a = "1234";
int b = int.Parse(a);
This code will change the string ‘a’ to an int of 1234. You can’t do math with a string, but you can with an int.
If the string a would be something like 123a4, line number 2 would give an example:
To avoid this exception or avoid handling any exception when parsing an int it’s better to use the TryParse().
int.TryParse()
string example = "1234";
int outcome;
bool isNumber = int.TryParse(example, out outcome);
if (isNumber)
Console.WriteLine($"The total should be {outcome + 5} 1239");
else
Console.WriteLine("Variable example is not a number");
On line 3 the int.TryParse is used. It has two parameters:
- string a
- out int result
string example = "123a4";
int outcome;
bool isNumber = int.TryParse(example, out outcome);
if (isNumber)
Console.WriteLine($"The total should be {outcome + 5} 1239");
else
Console.WriteLine("Variable example is not a number");
Convert.ToInt32()
This method can convert a string to an int. It works basically the same as the methods above and the outcome is the same.
string a = "2022";
int year = Convert.ToInt32(a);
If the string is a not a number, a FormatException will be thrown.
So, which one?
All three methods work and can convert a string to an int. But it depends on your situation. When you know the string will always be a number, no doubt about it, you can use int.Parse().
If you are handling user input and expect an integer, but the user can also enter other characters, use int.TryParse().
Convert.ToInt32() is a bit slower than int.TryParse() and it doesn’t give a null ArgumentNullException, whereas the others do give it when the value is NULL. The Convert class can do much more than just convert a string to an int.
Math
The int(eger) is very useful for maths, the one thing most of us hated back at school. Subtraction, adding, multiplication and division… It’s all possible. Just keep in mind that the outcome will have whole numbers only.
Basic math examples
int firstNumber = 5;
int secondNumber = 6;
int adding = firstNumber + secondNumber; // Will give 11
int substraction = firstNumber - secondNumber; // Will give -1
int multiplication = firstNumber * secondNumber; // Will give 30
int division = firstNumber / secondNumber; // Will give 0 (but is actually 0,8333333333)
Divide by zero
You can’t divide a number by zero. Not in C#, nor in a calculator. If you do this in C# you will get the exception DivideByZeroException.
// Gives compile error; application won't run.
int exampleOne = 6 / 0;
int firstNumber = 5;
int secondNumber = 0;
// Crashes when run and gives a DivideByZeroException exception
int adding = firstNumber / secondNumber;
Line 2 will give a compile error. This means Visual Studio will show a red curly line under the “6 / 0”. It’s smart enough to recognize the error.
Line 8 however won’t see the ‘error’ and you can run the application. The application will crash when reaching line 8 and give the exception.
Rounding up or down
In a previous example I showed that 5 / 6 is zero, but it’s actually 0,833333. In most case this number will be rounded up, making it 1. In C# this can be done with Math.Round().
The Math.Round() can round a number up or down. In this case, with the 5 / 6 we don’t have to do anything. The Math.Round() will see it’s above 0.5 and rounds it up. Two downsides… First, we need to convert one of the two variables to a decimal. It’s not hard, but not really nice. Second is that the Math.Round() returns a decimal, but we want to use int. Again, not hard, but not nice.
int firstNumber = 5;
int secondNumber = 6;
int result = (int)Math.Round(firstNumber / (decimal)secondNumber);
Validation
An int is by default 0 (zero) and it can only contain whole numbers, negative or positive. Validating an int is fairly easy. Usually, you check if an int is smaller, bigger, equal, or a combination of these.
int a = 1;
if (a == 0)
Console.WriteLine($"A is zero");
if (a > 1)
Console.WriteLine("A is larger than one");
if (a < 1)
Console.WriteLine("A is smaller than one");
if (a != 1)
Console.WriteLine("A is not one");
if (a >= 1)
Console.WriteLine("A is larger or equal than one");
if (a <= 1)
Console.WriteLine("A is larger or equal than one");
An int is not nullable, meaning you can’t assign NULL to it. But you can make it nullable by adding the question mark(?) after int. This is not something I would advise.
int? a = 1;
if (a.HasValue && a.Value > 1)
Console.WriteLine("A is not NULL and larger than one");
Conclusion for integers
I think that int is just as important as the string. You can use it anywhere and you will be using it everywhere. From simple math calculations to identifiers to enumerations. The only downside for int is that it can only contain whole numbers, so no decimals. For these, you will need to use other data types.
If you want to read more about the int and numbers, you can read the official Microsoft page.
If you think some method or trick is missing, let me know!