
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
How to capture null reference exception in C#?
It handles errors generated from referencing a null object. The Null reference exception occurs when you are looking to access member fields or function types that points to null.
Let’s say we have the following null string −
string str = null;
Now you try to get the length of the null string, then it would cause an exception −
If(str.Length == null) {}
Above the exception will be thrown. Now let us seen how to prevent the null pointer exception to be thrown −
Example
using System; class Program { static void Main() { int[] arr = new int[5] {1,2,3,4,5}; display(arr); arr = null; display(arr); } static void display(int[] arr) { if (arr == null) { return; } Console.WriteLine(arr.Rank); } }
Output
1
- Related Articles
- How to capture divide by zero exception in Java?
- How to capture file not found exception in Java?
- How to capture divide by zero exception in C#?
- How to capture file not found exception in C#?
- How to capture out of memory exception in C#?
- How to capture and print Python exception message?
- How to capture index out of range exception in C#?
- How to capture an exception raised by a Python Regular expression?
- How to Resolve Stale Element Reference Exception in Selenium WebDriver?
- How to capture out of array index out of bounds exception in Java?
- Null Pointer Exception in C#
- Null Pointer Exception in Java Programming
- What is Stale Element Reference Exception in Selenium Webdriver & How To Fix It?
- What is null pointer exception in Java and how to fix it?
- How to capture screenshots in Selenium?

Advertisements