最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Non-nullable field - Stack Overflow

programmeradmin2浏览0评论

If I write this:

private string boundText;

public String BoundText
{
    get { return boundText; }
    set
    {
        boundText = value;
        OnPropretyChanged("BoundText");
    }
}

I get this warning:

Warning CS8618 Non-nullable field 'boundText' must contain a non-null value when exiting the constructor. Consider declaring the field as nullable.

And if I write this:

private string boundText;

public String BoundText
{
    get { return boundText; }
    set
    {
        boundText = value;
        OnPropretyChanged("BoundText");
    }
}  = string.Empty;

I get this error :

Error CS8050 Only automatically implemented properties can have initializers.

If I write this:

private string boundText;

public String BoundText
{
    get { return boundText; }
    set
    {
        boundText = value;
        OnPropretyChanged("BoundText");
    }
}

I get this warning:

Warning CS8618 Non-nullable field 'boundText' must contain a non-null value when exiting the constructor. Consider declaring the field as nullable.

And if I write this:

private string boundText;

public String BoundText
{
    get { return boundText; }
    set
    {
        boundText = value;
        OnPropretyChanged("BoundText");
    }
}  = string.Empty;

I get this error :

Error CS8050 Only automatically implemented properties can have initializers.

Share Improve this question edited Mar 13 at 16:11 marc_s 756k184 gold badges1.4k silver badges1.5k bronze badges asked Mar 13 at 14:41 guilherme franceschiguilherme franceschi 454 bronze badges 9
  • 1 what is boundText? – MakePeaceGreatAgain Commented Mar 13 at 14:43
  • empty and null is not the same – LMA Commented Mar 13 at 14:45
  • 1 private string boundText = string.Empty; - here is where you assign the default value. – Clemens Commented Mar 13 at 14:45
  • @Clemens thats a dirty wrap around since you deny any nullhandling for the future – LMA Commented Mar 13 at 14:48
  • 1 private string? boundText; - This is the proper way to handle it for future null handling – Charles Henington Commented Mar 14 at 6:54
 |  Show 4 more comments

1 Answer 1

Reset to default 1

You need to assign boundText (not BoundText) a default value.

Should be something like that

private string boundText = string.Empty;
public string BoundText
{
    get => boundText;
    set
    {
        boundText = value;
        OnPropertyChanged(nameof(BoundText));
    }
}

It doesn't really address the issue but i also advice you to use nameof instead of hardcoding string value

发布评论

评论列表(0)

  1. 暂无评论