Skip to content

Prefer IParsable over Convert #81

@Seb-stian

Description

@Seb-stian

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions