Datatype Conversions in C#
Hello friends, I hope you all are doing great. In today's tutorial, we are gonna have a look at Datatype Conversions in C#. We have discussed
C# Data Types in our 3rd tutorial and today we will discuss How to convert one datatype into another.
If you are working on some complex project, then you have to convert one form of data into another i.e. let's say you are getting bill value from barcode reader, this value must be a string and if you want to apply any arithmetic operation on it then you need to convert that string into integer or float. So, let's get started with Datatype Conversions in C#:
Datatype Conversions in C#
- If you are working on some data driven application, then there's always a need to convert one form of data into another and that's where Datatype Conversions are required.
- Few conversions doesn't require any method or class i.e. if we want to convert an integer into float then that can easily be done by the compiler, as there's no chance of data loss.
- Such conversions are called Implicit Conversions, here's an example:
- You can see in above figure that compiler has automatically converted integer into float.
- But if we want to convert a float (let's say 313.56) into integer then we can't do that as integer doesn't have the decimal part.
- So, if we want to convert a float into integer, we will get a compiler error i.e. overflow exception.
- In order to perform such conversions we have to use Explicit Conversions method, pre-defined in C#.
- There are two options for Explicit Conversions:
- Use Cast Operator.
- Use Convert class of C#.
- Both of these methods are shown in below figure:
- Now you can see in above figure that the Cast Operator (int) has just taken the main value and simply ignored the decimal/fractional part.
- While the Convert Class (Convert.ToInt32) has rounded off the number and didn't ignore the decimal part.
String Conversion in C#
- Normally the data received from external/hardware devices, is in the form of strings and we need to convert it into integer or float etc. to perform arithmetic operations.
- There are two options available for String Conversions in c#, which are:
- Here's the implementation of Parse Method for String to integer conversion, in below figure:
- But there's a drawback in Parse that if the string contains alphabetical / special characters then it will create an error and couldn't convert the string into integer.
- So, in order to avoid error, we should use TryParse method, as shown in below figure:
- As you can see in above figure, TryParse takes two parameters:
- First one must be a string, which you want to convert.
- Second one must be an integer, in which the value will be saved.
- Moreover, TryParse method also returns a Boolean type, which will be:
- True, if the conversion is successful.
- False, if the conversion is unsuccessful.
- I have provided a string "323ABC" whcih contains alphabetical characters, that's why ConversionCheck is false and we are not getting any value in our integer.
- Here's a screenshot of one successful conversion of TryParse method:
- Now TryParse is returning True as the conversion is successful and our output integer variable got updated.
- Here's the code used in today's tutorial:
using System;
namespace TEPProject
{
class Program
{
static void Main(string[] args)
{
Console.Write("\n\nwww.TheEngineeringProjects.com\n");
string Num1 = "323";
bool ConversionCheck = int.TryParse(Num1, out int Num2);
Console.WriteLine("\nValue of Num2 : {0}", Num2);
Console.WriteLine("\nValue of ConversionCheck : {0}", ConversionCheck);
if(!ConversionCheck)
{
Console.WriteLine("\nString contains non-numeric Values.");
}
else
{
Console.WriteLine("\nOur Converted int : {0}", Num2);
}
}
}
}
So, that was all about the Datatype Conversions in C#. I hope you have enjoyed today's tutorial. In the next tutorial, we will have a look at
How to use Arrays in C#. Till then take care & have fun !!! :)
Common Operators in C#
Hello friends, I hope you all are doing great. In today's tutorial, we are going to have a look at few Common Operators in C#. It's 4th tutorial in C# series and before going forward, we have to first understand the working operation of these C# operators.
We have a lot of operators in C# but I have discussed few of them, which are most commonly used. If you got into any trouble then ask in comments. So, let's get started with Common Operators in C#:
Common Operators in C#
- Operators are used to create a link, relation or operation between two entities/variables. Few of these C# operators are as follows:
- Assignment Operator ( = )
- Arithmetic Operators ( + , - , * , / , % )
- Comparison Operators ( == , != , > , < , >= , <= )
- Conditional Operators ( && , | | )
- Ternary Operator ( ? : )
- Null Coalescing Operator ( ?? )
- Escape Sequence ( / )
- Verbatim Literal ( @ )
- Let's discuss them one by one in detail:
1. Assignment Operator ( = )
- Assignment Operator is used to assign a value from one entity to another.
- Let's say we initialize an integer with value 5, so what we need to write is int i = 5; so this assignment operator has assigned a value of 5 to integer i.
2. Arithmetic Operators ( + , - , * , / , % )
- Arithmetic Operators ( + , - , * , / , % ) are used for performing different mathematical operations between two entities/variables.
- Each arithmetic operator has its own mathematical operation associated with it. For example:
- ( + ) is used to add two numbers i.e. int a = 5 + 10; so compiler will first apply the arithmetic operator (+) and will add 5 & 10 and after that will use assignment operator to assign the value 15 to variable a.
- ( - ) is used to subtract two numbers i.e. int b = 10 - 5; result will be 5.
- ( * ) is use to multiply two numbers i.e. int c = 10 * 5; result will be 50.
- ( / ) is used to divide two numbers i.e. int d = 10 / 2; result will be 5.
- ( % ) is used to get the remainder of two numbers i.e. int e = 22 % 4; result will be 2.
3. Comparison Operators ( == , != , > , < , >= , <= )
- Comparison Operators ( == , != , > , < , >= , <= ) are used to compare two entities with one another.
- We will discuss them in detail in Loops section while discussing if loop.
- a == b, it will check whether a is equal to b.
- a != b, a is not equal to b.
- a > b, a is greater than b.
- a < b, a is less than b.
- a >= b, a is greater than or equal to b.
- a <= b, a is less than or equal to b.
- I am using few Comparison operators in this right figure.
4. Conditional Operators ( && , | | )
- Conditional Operators ( && , | | ) are used to create a relation between two conditions.
- This one will also be discussed in more detail in IF Loops section.
- && , It is pronounced as AND, this operator makes sure that both conditions must be true.
- | | , It is pronounced as OR, this operator returns TRUE if either of the two conditions is true.
- I have placed a conditional operator in right figure, I have placed a check that value must be greater than 10 and less than 20.
5. Ternary Operator ( ? : )
- Ternary operator is one of the coolest feature of C# and comes quite handy at times.
- It's a simple form of if loop, which reduces the IF Else Loop code in single line. We will discuss it in C# IF Loop lecture.
6. Null Coalescing Operator ( ?? )
- Null Coalescing Operator ( ?? ) is used to convert nullable value into non-nullable value.
- Let's say we have two integers a and b defined as:
int? a = 15; (nullable variable)
int b = 0; (non-nullable variable)
- Now we want to save value of a into b so if you write a = b; compiler will generate an error.
- So, in order to do that you need to use Null Coalescing Operator ( ?? ) as follow:
int b = a ?? 0;
- if the value of a is null, then b will become 0. It's called the default value, you can set it to anything, I've made it 0.
Complete Code
- Here's the complete code used in this tutorial:
using System;
namespace TEPProject
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter Numer 1: ");
int Num1 = int.Parse(Console.ReadLine());
Console.Write("Enter Numer 2: ");
int Num2 = int.Parse(Console.ReadLine());
int Total = Num1 + Num2;
if (Total > 10 && Total < 25)
{
Console.WriteLine("Total count is {0}", Total);
}
else
{
Console.WriteLine("Total count is less than 10 or greater than 25");
}
}
}
}
I hope you have learnt something from today's tutorial. Let me know if you have any questions in comments. Take care & have fun !!! :)