Tal Tal - 9 months ago 67
ASP.NET (C#) Question

Null string exception

Before i ask my question i need to mention that i looked up in the site to solve the problem but i didnt find nothing.

Here is my function :

public string GetAccessToken(int agencyId)
string retrunString = null;
Token fbToken = tokenMgr.Get(agencyId, "FacebookInsights");
if (String.IsNullOrWhiteSpace(fbToken.AccessToken)) **
return retrunString;
return fbToken.AccessToken;

When Token is an object which include a String field name : AccessToken.

When i debug the code and reach the line with the ' ** ' when fbToken.AccessToken is NULL , I get an exception " Object reference not set to an instance of an object."

When i looked up in other threads they suggest to use String.IsNullOrWhiteSpace , but it didnt solve the problem and i keep getting the error.

I would greatly appreciate any help , thanks in advance!

Answer Source

fbToken is null, not fbToken.AccessToken. Use something like this:

if ( fbToken == null || String.IsNullOrWhiteSpace(fbToken.AccessToken) )

New C# 6.0 allows you to do null propagation to accomplish this as well:

if ( String.IsNullOrWhiteSpace(fbToken?.AccessToken) )