简体   繁体   中英

Check if object is null before calling method. Object reference not set to an instance of an object

I keep getting a NullReferenceException. How do I initialize my doubles to determine if they are null? Sorry for the noob question :(

private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{

    //gets new value of slider
    double newValue = (double)Math.Round(e.NewValue);

    //gets current/previous value of slider
    double  currentValue = slider1.Value;

    //gets sum of previous value - new value 
    double valueSum = (double)Math.Round(currentValue - newValue);

To answer your Bonus question:

The previous value of the slider is provided by the RoutedPropertyChangedEventArgs<T> and it is stored in the property OldValue .

To answer your question:

The only place in your code that can throw a NullReferenceException is when slider1 is not initialized and is null . I assume that the method slider1_ValueChanged is called by the UI, so that parameter sender and e are initialized. So try to attach a debugger an see where the Exception is thrown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM