Skip to content

Commit

Permalink
[Term Entry] Dart Type Conversion: .tryParse()
Browse files Browse the repository at this point in the history
* Added doc content

* Added finalised doc items

* Correct grammatical error

* Added additional tags to tryPasre.md term entry

Co-authored-by: mamtawardhani <53176352+mamtawardhani@users.noreply.github.com>

* Added additional tags to tryPasre.md term entry

Co-authored-by: mamtawardhani <53176352+mamtawardhani@users.noreply.github.com>

* Updated learning paths

Co-authored-by: mamtawardhani <53176352+mamtawardhani@users.noreply.github.com>

* Updated description

Co-authored-by: mamtawardhani <53176352+mamtawardhani@users.noreply.github.com>

* Updated example explanation.

Co-authored-by: mamtawardhani <53176352+mamtawardhani@users.noreply.github.com>

* Updated Syntax

Co-authored-by: mamtawardhani <53176352+mamtawardhani@users.noreply.github.com>

* Update content/dart/concepts/type-conversion/terms/tryParse/tryParse.md

Co-authored-by: mamtawardhani <53176352+mamtawardhani@users.noreply.github.com>

* Removed Codebyte and updated example

* Update syntax explanation

Co-authored-by: mamtawardhani <53176352+mamtawardhani@users.noreply.github.com>

* Minor changes

---------
  • Loading branch information
lou-pastorino committed May 1, 2024
1 parent 437ffda commit 26ca81e
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions content/dart/concepts/type-conversion/terms/tryParse/tryParse.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
---
Title: '.tryParse()'
Description: 'Parses a string and converts it into the given data type.'
Subjects:
- 'Computer Science'
- 'Developer Tools'
Tags:
- 'Dart'
- 'Data Types'
- 'Methods'
- 'Strings'
CatalogContent:
- 'learn-dart'
- 'paths/computer-science'
---

In Dart, **`.tryParse()`** is a static method available on several [data types](https://www.codecademy.com/resources/docs/dart/data-types), such as `int` and `double`. When called on a `string`, the `.tryParse()` method parses the string and converts it into the given data type if the parsing is successful. However, if parsing fails due to an invalid format in the string, the method returns `null`.

## Syntax

```pseudo
dataType.tryParse(stringToParse)
```

- `stringToParse`: Represents the `string` to be converted into the desired data type.
- `dataType`: Represents the data type to be used to parse `stringToParse`.

## Example

```dart
void main() {
String input = '42';
int? parsedInt = int.tryParse(input);
if (parsedInt != null) {
print('Parsed integer: $parsedInt');
} else {
print('Failed to parse the string as an integer!');
}
}
```

The above code returns the following output:

```shell
Parsed integer: 42
```

0 comments on commit 26ca81e

Please sign in to comment.