1

Reading the Settings for the first time (-before they've been set) throws an Object reference not set to an instance of an object. exception.

Setting a default value using DefaultSettingValueAttribute cannot be done in the real case because it's not a simple type like in the my example of an int, and can't be described as a string. From the docs:

DefaultSettingValueAttribute requires that the default value can be represented as a string.

How should this be avoided?

More info:

Of course I can wrap it in a try-catch block, but that should be left for exceptional cases, whereas this is a normal thing - every user who will use the application for the first time will encounter this. And trying every time because of that first time seems wrong.

So what’s the correct solution?

Here's the code:

public class MySettings : ApplicationSettingsBase
{
    [UserScopedSettingAttribute()]
    public int MyInt
    {
        get { return (int)(this["MyInt"]); } // Object reference not set to an instance of an object.
        set { this["MyInt"] = value; }
    }
}

And called so:

MySettings s = new MySettings();
int i = s.MyInt;

1 Answer 1

0

You need to specify a default value for the setting. I think that should prevent it from memory.

If you can't specify a default, put a check in the getter to see if its null, if it is initialize it to your own default value.

get { 

      if(this["MyInt"] == null)
          this["MyInt"] = 0;

      return (int)(this["MyInt"]); 
    }
2
  • Thanks. However, The real case is of a complicated type, not an int - so it can't have a default value (because it can't be described as a string.)
    – ispiro
    Jul 30, 2013 at 19:34
  • I'll give it a try. I just checked and saw that the exceptin is not by calling the object itself...
    – ispiro
    Jul 30, 2013 at 19:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.