-1

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;
        else
            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!

Tal
  • 235
  • 5
  • 13

3 Answers3

2

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) )
Blue
  • 22,608
  • 7
  • 62
  • 92
1

Write it like this. Check Null-conditional Operators

if(String.IsNullOrWhiteSpace(fbToken?.AccessToken))
{
    //your stuff
}
mybirthname
  • 17,949
  • 3
  • 31
  • 55
0

You have to validate the object fbToken and not his member AccessToken.

public string GetAccessToken(int agencyId)
{
    var fbToken = tokenMgr.Get(agencyId, "FacebookInsights");  
    return (fbToken == null) ? null : fbToken.AccessToken;
}
Andre Hofmeister
  • 3,185
  • 11
  • 51
  • 74