简体   繁体   中英

Why Automatically implemented properties must define both get and set accessors

When we define a property like

    public string Name {get; set;}

dot.net can make our properties code. but when we use

    public string Name {get;}
    public string Name {set;}

we face with

'Hajloo.SomeThing.PropertyName.set' must declare a body because it is not marked abstract or extern. Automatically implemented properties must define both get and set accessors.

Actually why the compiler can't determine the property and make code automatically? What's the problem?

Because the auto-implemented properties generate their own backing store for the property values. You have no access to the internal store.

Implementing a property with

  • just get : means you can only retrieve the values. You can't ever set the property value (even in the containing class)
  • just set : means you can only set the values. You can't retrieve the property value.

for a normal property

private int _data;
public int Data{  get { return _data } };

Here the parent class can do the following somewhere else in the class ( which it can't with auto props)

_data = 100;

Note: You can define an auto-prop like this (which is how I use it the most).

public int Data { get; private set;}

This means that the property can't be set by external clients of the class. However the containing class itself can set the property multiple times via this.Data = x; within the class definition.

如果没有setter,则该属性永远不会具有除默认值之外的任何内容,因此不会用于任何目的。

A more modern scenario for receiving this error is building code that uses C#6 syntax using a version of VisualStudio that is less than VS 2015 (or using MsBuild that is less than 14).

In C#6.0 it is allowable to have autoProperties that do not have a setter (they are assumed to be a private set).

Try compiling with VS2015+ or msbuild 14+ .. or modify the code so that all autoProperties have a setter.

How to assign default value in case of null in C#

" Assign default value to object if value is null in c# [duplicate] " This top was closed saying that it got ansewred by this one. However everything posted here does not answer that topic in my opinion, so I'm posting in here (not able to post in there) what worked for me and I was looking for:

decimal default_value = 0.00m;
return (decimal?)json['JSON_KEY'] ?? default_value;

In the example above I was trying to set a default value in case extraction of a decimal from a json is null (like we can do in kotlin or swift). Ps: This implementation works for new versions of .NET framework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM