How to handle 'nullreferenceexception in c#'?

Example:

string str = null;
int len = str.Length;

Attempting to call a method on a null reference.

Solution:

This exception occurs when you try to access members of an object that is `null`. Always check for `null` before accessing object members.


if(str != null) {
    int len = str.Length;
}

Beginner's Guide to C#