I pass this value to the parameter:

Properties.Settings.Default["Имя параметра"] = value; 

The question is as follows. How to determine that the type of value being set corresponds to the type of the parameter? How to cast the value value to the parameter type?

  public void SetProperty(string nameProperty, string valueProperty) { ErrorManipulation(null, enumResultCode.Success);//Устанавливаем значения по умолчанию //Сохраняем параметр //string nameProperty = value; //Наименование параметра Type typeProperty = Properties.Settings.Default[nameProperty].GetType(); //Тип значения параметра try { Properties.Settings.Default[nameProperty] = Convert.ChangeType(valueProperty, typeProperty); //передаваемое значение приводим к типу параметра PropportiesSave(); //сохраняем значение параметра } catch (Exception e) //Если не удалось преобразовать значение { ErrorManipulation(string.Format("{0}; Источник: {1}", e.Message, e.Source), enumResultCode.Error);//Устанавливаем значения при возникновении исключения } } 

    2 answers 2

    To cast Value to a parameter type:

     Properties.Settings.Default["Имя параметра"] = Convert.ChangeType(Value, Properties.Settings.Default["Имя параметра"].GetType()); Properties.Settings.Default.Save(); 
    • Can you edit the answer so that in case of editing the question it remains valid? Something like "In order to cast the value value to the parameter type ...". - Vadim Ovchinnikov
    • This does not work if the Properties.Settings.Default["Имя параметра"] is null . - VladD

    A more direct method is to use ready-typed properties.

    When you create a parameter value with the name MyParameter some type, you create a property with the same name and the same type. Therefore, the easiest way to work is through the property: code

     Properties.Settings.Default.MyParameter = value; 

    just won't compile if the value type is invalid.


    If the parameter name is unknown at compile time, it is a little more complicated. To begin with, think about whether you chose the right task: why do you need a property with an unknown name? Maybe you just need a Dictionary ?

    If, nevertheless, you just need the Settings , you can get the type by name using the construction

     Type propertyType = Properties.Settings.Default.Properties["TestSetting"].PropertyType; 

    Having a type, you can check whether the assignment is possible:

     if (propertyType.IsAssignableFrom(value.GetType())) { ... 

    Update:

    If the target type is enum , and the source value is represented as a string, then it is best to do so.

     enum Colors { Red, Green, Blue, Yellow, Error } 
     Colors color; if (!Enum.TryParse<Colors>(value, out color)) { color = Colors.Error; // вывести сообщение об ошибке } Properties.Settings.Default.MyParameter = color; 

    A slightly more advanced version is considered here .

    • And if Value = "123", it will not work either. - Alexander Puzanov
    • @AlexanderPuzanov: Depends on the type of parameter in Settings. - VladD
    • Let's say the type is int. In this example, the string will not be converted to a number. - Alexander Puzanov
    • one
      @AlexanderPuzanov: Well, yes. But is it good? Or do you need to try to convert in this case too? And what if the line is not a number, then what should happen? - VladD
    • This is a separate processing of the supplied value - Alexander Puzanov