0

I am Developing Universal windows app,

I want to Send user Directly to Companies Screen if user Re-Launching the app, i am using following block of code but it gives me Null reference exception

 Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
        Windows.Storage.ApplicationDataCompositeValue composite =(Windows.Storage.ApplicationDataCompositeValue)localSettings.Values["exampleCompositeSetting"];
        if (composite == null)
        {
            // No data
        }
        else
        {
            string user = composite["UserId"].ToString();
            Frame.Navigate(typeof(Companies));              
        }

Any one Help me on this Please.

Thanks, Srinivas.

srinivas challa
  • 193
  • 6
  • 14
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Stefan Over Nov 03 '17 at 12:00

1 Answers1

1

If there is no data, this will be null.

localSettings.Values["exampleCompositeSetting"];

If you cast null to another type, you will get a NullReferenceException.

Use as keyword for this casting. Read docs for “as”, and also “is” keywords if you are not familiar with them.

 Windows.Storage.ApplicationDataCompositeValue composite = localSettings.Values["exampleCompositeSetting"] as (Windows.Storage.ApplicationDataCompositeValue);

It won’t throw exception if the value is null, you just need to check if the result is null before using the result.

Also refer to this answer: as vs classic casting

kennyzx
  • 12,845
  • 6
  • 39
  • 83