-2

If null value is assigned to SettingCode, I want the value to instead be set to "" or empty string.

[Required(AllowEmptyStrings = true)]
[StringLength(20)]
public string SettingCode { get; set; } 
bitshift
  • 6,026
  • 11
  • 44
  • 108
  • Did you even try anything? getters and setters are nothing but methods, so you can ady code there. However this assumes a body for each. Auto-properties hide that body away from you. See here for example: https://stackoverflow.com/questions/6127290/c-sharp-add-validation-on-a-setter-method – MakePeaceGreatAgain Dec 13 '19 at 14:16
  • 6
    You just need to manually implement the `set` and `get` methods. – crashmstr Dec 13 '19 at 14:16
  • 1
    Use a computed property. – xTwisteDx Dec 13 '19 at 14:18
  • It´s even mentioned in the docs: https://learn.microsoft.com/dotnet/csharp/programming-guide/classes-and-structs/properties – MakePeaceGreatAgain Dec 13 '19 at 14:18

3 Answers3

3

I guess you are using an OR/M to feed this property. So you have on the DB a nullable field, and you just don't want null in the code. This usually is not a good idea, since it will possibly lead to other problems while you persist back the data. However, if this is the case, and you want to do it, use a backing field:

string settingCode;

[Required(AllowEmptyStrings = true)]
[StringLength(20)]
public string SettingCode { get {return settingCode??"";} set { settingCode=value; } } 
Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
2

This is as simple as declaring a local variable to hold the value and implementing some code in set:

private string _settingCode;

[Required(AllowEmptyStrings = true)]
[StringLength(20)]
public string SettingCode
{
    get { return _settingCode; }
    set
    {
        _settingCode = value == null ? string.Empty : value;
    }
} 
Martin
  • 16,093
  • 1
  • 29
  • 48
1

I would use a property + field to achieve that instead of an auto-implemented property :

private string _settingCode;

[Required(AllowEmptyStrings = true)]
[StringLength(20)]
public string SettingCode
{
    get { return _settingCode; }
    set { _settingCode = value?? string.Empty; }
}
Cid
  • 14,968
  • 4
  • 30
  • 45