开发者

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?


  1. You do not need to call .ToString().
  2. 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 a String object.
  • (...).ToString() Returns the same String object
  • string.Format("{0}! ", (...)): Returns a new String object containing the original string followed by !.
  • Convert.ToDecimal((...)): Tries to parse that into a Decimal 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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜