Вопрос

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;
Это было полезно?

Решение

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"]); 
    }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top