Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prefer IParsable over Convert #81

Open
Seb-stian opened this issue Mar 1, 2023 · 1 comment
Open

Prefer IParsable over Convert #81

Seb-stian opened this issue Mar 1, 2023 · 1 comment

Comments

@Seb-stian
Copy link
Contributor

For a long time now, it was preferable to use int.Parse(string) over Convert.ToInt32(string). If you look at the implementation of ToInt32, you can see that it internally calls int.Parse(string), BUT returns 0 when input is null. This behaviour is rarely desirable. Even better than Parse is TryParse, since it is cleaner and performs better than handling exceptions with try catch. Parse is of course better when it comes to writing a simple code snippet for a lecture.

In modern .NET (version 7+) there is IParsable<TSelf> interface that reinforces the suggested pattern even further.

My suggested changes are to reflect these facts in lecture notes (and in related code examples).

The only relevant code example I could find with VS search was in CodeDemonstrations.cs:

Console.WriteLine("Waiting for input (number)...");
int input = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"Input: {input}");

So that's not too bad, but the lack of it in lecture notes is worse.

@pluskal
Copy link
Contributor

pluskal commented Mar 3, 2023

Nice catch. Feel free to add PR with change to the place you feel is appropriate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants