RKh
RKh

Reputation: 14159

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?

Upvotes: 0

Views: 138

Answers (2)

Jim Mischel
Jim Mischel

Reputation: 134045

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
}

Upvotes: 1

SLaks
SLaks

Reputation: 887797

  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

Upvotes: 4

Related Questions