Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

sagnikchakraborti
sagnikchakraborti
929 Points

When should I use (int) and int.Parse()? What's the difference?

For example,

int(2.3 + 3) gives us 5, similarly can we not use int.Parse(2.3 + 3) here ?

And

string entry = Console.ReadLine(); int testNumber = int.Parse(entry)

can we not write

int testNumber = int(entry) ?

2 Answers

Steven Parker
Steven Parker
231,210 Points

:point_right: You may be confusing C# with another language (perhaps Python?)

There's no int() function in C#. Perhaps you're thinking of the type casting operator (int). For example, (int)(2.3 + 3) would indeed return 5.

Also, you cannot use int.Parse(2.3 + 3), since int.Parse takes a string argument. But you could, for example, do int.Parse("5.3"). That's what makes it particularly useful for converting input from a Console.Readline into a number.

sagnikchakraborti
sagnikchakraborti
929 Points

Aha. My mistake. I meant (int). Yes got confused with some other languages. So, (int) can be used only to change float or double etc to integer whereas int.Parse() can be used to change String to Integer. Am I right? or missing anything else?

Roman Fincher
Roman Fincher
18,267 Points

Essentially, the difference here is between casting and parsing. See Marc Gravell's response on this forum for a useful summary: MSDN forums: casting vs. converting vs. parsing.

You may be aware of this, but I thought I'd mention that it's also worth looking into int.TryParse() for this purpose. This allows you to avoid exceptions that might occur if the value cannot be parsed. For instance:

var myInteger = int.Parse("this is a string")

would throw an exception but running

var value = "this is a string";
int parseInt;
if int.TryParse(value, out parseInt) 
{
    var myInteger = parseInt;
}

would not throw an exception and would only set myInteger if the string is successfully parsed. See the C# streams and data processing course for more info!