简体   繁体   中英

C# properties, what is the difference between these two implementations?

What is the difference between below two implementations of POCO classes?

class Test
    {
        int _var1;
        string _var2;

        public int var1
        {
            get
            {
                return _var1;
            }
            set
            {
                _var1 = value;
            }
        }

        public string var2
        {
            get
            {
                return _var2;
            }
            set
            {
                _var2 = value;
            }
        }
    }

and

class Test2
    {
        int _var1;
        string _var2;

        public int var1
        {
            get;
            set;
        }

        public string var2
        {
            get;
            set;
        }
    }

The first is regular property implementation with a backing field, the second is auto-implemented properties and the fields won't be used as the compiler will generate backing fields for you.

Auto-implemented properties save you from having to write the backing fields and the boilerplate code to access them, the compiler creates C#-unnameable backing fields in the IL that won't collide with other field names in the class.

The end effect is they are equivalent , though I have heard of serialization issues with auto-properties due to the name of the backing field, let me find the question... sorry I can't seem to find it at the moment.

Functionality wise no difference. Compiler will generate the first version from 2nd.

The second implementation is called Auto-Properties , which was a feature introduced in framework 3.0.

The first implementation was the traditional way prior to framework 3.0.

See this link for an example of auto-properties. Under the hood, the auto-properties will generate the backing fields for you.

Take a look at this link too, for arguments against their use .

You can access the underlying directly in the first implementation.

But in truth the second implementation generates the first behind the scenes, except with other backing properties.

The properties are the same functionally, but in the second your private variables _var1 and _var2 will never be used.

In the first, you are returning instances of your private variables using properties.

In the second, the compiler generates the fields and handles the assignment of the them behind the scenes so you do not need to explicitly declare them.

In the second case, the compiler will automatically add a field for you, and wrap the property. It's basically the equivalent to doing it with a backing field.

两者对于开发者来说都是一样的

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