Conversion of one type of variable into another type of variable is called casting, as in the following:
int i = 10;
float k = 20.0f;
i = k; // not possible
i = (int)k; //again possible
Error in Casting

I am dividing this article into two parts, in the first part I'll explain why we can't convert an int into a short directly but the opposite is possible and in the second part I'll explain the other data type, float, by comparing it with int.
Part: 1 [int VS short]
As I said above, an int cannot be directly converted into a short but the opposite is possible. But I will tell you in this article how can you convert an int into a short too.
Explanation
int i = 10;
short j = 5;
j = i; // not possible
Now the question is how to convert int into short, so here we go-
int i = 10;
short j = 5;
j = (short)i; // now possible
Example
Snippet: 1.1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Hello_Word
{
class Program
{
static void Main(string[] args)
{
int i = 10;
short j = 5;
float k = 20.0f;
i = j;
j = (short)i;
Console.WriteLine("value is: " + j);
k = i;
// i = k;
Console.ReadLine();
}
}
}
Now I will show you what changes occur whenever we convert a large data type into a smaller data type.
(In this case it is for an int to a short.)
Snippet: 1.2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Hello_Word
{
class Program
{
static void Main(string[] args)
{
int i = 100000;
short j = 5;
float k = 20.0f;
// i = j;
j = (short)i;
Console.WriteLine("value is: " + j);
k = i;
// i = k;
Console.ReadLine();
}
}
}



Comments
Join the conversation! Your thoughts help the community grow.