Is there a better way to do this?

Started by
2 comments, last by NightCreature83 10 years, 9 months ago

Is there a better way of doing this more efficiently and better way? It runs and calculates the area but I think there is a better way.

Code Below:

[source lang="csharp"]

namespace LearningCsharp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter length");
string length = Console.ReadLine();
int.Parse(length);
int newLength = Convert.ToInt32(length);
Console.WriteLine("Enter width");
string width = Console.ReadLine();
int.Parse(width);
int newWidth = Convert.ToInt32(width);
Console.WriteLine(newLength * newWidth + "cm");
Console.ReadLine();
}
}
}
[/source]
Advertisement

Delete the int.Parse lines.

Convert.ToInt32(string) and int.Parse(string) are identical. Convert.ToInt32's main use is that you can pass it things besides strings and convert those to an int as well.

Choose one or the other but not both.

Also Parse is not exception safe so you would have to use a try catch clause around it. There is a TryParse function as well that is exception safe.

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, theHunter, theHunter: Primal, Mad Max, Watch Dogs: Legion

This topic is closed to new replies.

Advertisement