How to get rid of conversion overheads?
Take this example:
customer.Salary = Convert.ToDecimal(string.Format("{0}! ", Console.ReadLine().ToString()));
(1) Why in C# we need to always put .ToString() to get it right?
(2) Convert.To... Doesn't it creates overheads unnecessarily?
Further in the below given code: It gives error: "Input string was not in a correct format", after accepting user input.
// Main begins program execution.
public static void Main()
{
Customer customer = new Customer();
// Write to console/get input
Console.Write("Enter customer's salary: ");
customer.Salary = Convert.ToDecimal(string.Format("{0}! "开发者_运维问答, Console.ReadLine().ToString()));
Console.WriteLine("Salary in class variable is: {0}", customer.Salary.ToString());
Console.Read();
}
class Customer
{
public Decimal Salary { get; set; }
}
Here again, either I must use:
string sal = Convert.ToDecimal(string.Format("{0}! ", Console.ReadLine().ToString()));
customer.Salary = Convert.ToDecimal(sal);
Or, I must change the data type itself in the Customer class.
Can this overhead be avoided with anything in Generics?
- You do not need to call
.ToString()
. - Yes, it does.
You're trying to write
customer.Salary = Decimal.Parse(Console.ReadLine());
Your current code does the following:
Console.ReadLine()
: Reads a line from the console, returning aString
object.(...).ToString()
Returns the sameString
objectstring.Format("{0}! ", (...))
: Returns a newString
object containing the original string followed by!
.Convert.ToDecimal((...))
: Tries to parse that into aDecimal
value.
Since the string ends with!
, it fails
I think you'll be happier if you use Decimal.Parse
or Decimal.TryParse
to do the conversions, rather than relying on Convert.ToDecimal
. You can write:
Decimal tempSal;
string sal = Console.ReadLine();
if (Decimal.TryParse(sal, out tempSal))
{
customer.Salary = tempSal;
}
else
{
// user entered bad data
}
精彩评论