- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to parse a string into a nullable int in C#?
C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values.
C# 2.0 introduced nullable types that allow you to assign null to value type variables. You can declare nullable types using Nullable where T is a type.
Nullable types can only be used with value types.
The Value property will throw an InvalidOperationException if value is null; otherwise it will return the value.
The HasValue property returns true if the variable contains a value, or false if it is null.
You can only use == and != operators with a nullable type. For other comparison use the Nullable static class.
Nested nullable types are not allowed. Nullable<Nullable<int>> i; will give a compile time error.
Example 1
static class Program{ static void Main(string[] args){ string s = "123"; System.Console.WriteLine(s.ToNullableInt()); Console.ReadLine(); } static int? ToNullableInt(this string s){ int i; if (int.TryParse(s, out i)) return i; return null; } }
Output
123
When Null is passed to the extenstion method it doesn't print any value
static class Program{ static void Main(string[] args){ string s = null; System.Console.WriteLine(s.ToNullableInt()); Console.ReadLine(); } static int? ToNullableInt(this string s){ int i; if (int.TryParse(s, out i)) return i; return null; } }
Output
- Related Articles
- How to parse a string to an int in C++?
- How to convert a string into int in C#?
- How to parse a string to float or int in python?
- How to convert a String into int in Java?
- How to convert hex string into int in Python?
- C++ Program to Convert int Type Variables into String
- How to convert a single char into an int in C++
- How to concatenate a std::string and an int in C++?
- How to check if a C/C++ string is an int?
- How to parse a string from a JavaScript array?
- How to copy a String into another String in C#
- How to create a tuple with string and int items in C#?
- How to convert an int to string in C++?
- C# Nullable Datetime
- How to convert a String to an int in Java
