Why do we need to convert the data types? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why do we need to convert the data types?

There is no need to convert the data types. For example:- We write String a; a=Console.ReadLine(); And convert int b=Convert.ToInt32(Console.ReadLine()) ; Simply we can do String a=Console.ReadLine(); int b=Console.ReadLine() ; //here the data types have already been taken by us.

11th Jul 2016, 11:48 AM
Sarthak Mathur
Sarthak Mathur - avatar
3 Answers
+ 4
Console.ReadLine() return a string, you need to manually convert it. It does not give it back as a specific type else than string as its not ensured that the entered string actually is meant to be an int. You can write your own function though using generic type arguments. T ReadLine<T>() { return (T) System.Convert.ChangeType(Console.ReadLine(), typeof(T)); } You'd use it like this then: string a = ReadLine<string>(); int b = ReadLine<int>(); float c = ReadLine<float>(); Its not the best way though.. Ideally you'd be using for example int.TryParse to prevent errors if the entered string is no valid int.
11th Jul 2016, 2:50 PM
LetSPlaYRagE23
LetSPlaYRagE23 - avatar
+ 4
To Sarthak, 👆 Your int b = Console.ReadLine() will not work, it'll produce an ❌ error. Just like what @LetSPlaYRagE23 © said, Console.ReadLine() returns a String value. ✔ And you cannot 🚫 save a String value to a variable with an Integer Data Type. You may either use: 🅰 int b = int.Parse(Console.ReadLine()); (just like what @LetSPlaYRagE23 © said) or 🅱 int b = Convert.ToInt32(Console.ReadLine()); And regarding your question in why we need to convert Data Types. ❔ That is because, variables only accept values that are of similar Data Type with them. ✔ Hope that helps! 😁
11th Jul 2016, 3:40 PM
Erwin Mesias
Erwin Mesias - avatar
+ 1
a simple thing you should remember is...watever u input from console.readline() that takes ur input as string....so it must be converted if u want to assign it to an integer type
11th Jul 2016, 7:04 PM
Santhosh