开发者

Can I remove { get; set; } in C# [duplicate]

开发者 https://www.devze.com 2023-02-23 06:50 出处:网络
This question already has answers here: Closed 11 years a开发者_如何学Gogo. Possible Duplicate: C#: Can I remove “{ get; set; }”?
This question already has answers here: Closed 11 years a开发者_如何学Gogo.

Possible Duplicate:

C#: Can I remove “{ get; set; }”?

My code has hundreds of lines that look like this:

public string abc { get; set; }
public string def { get; set; }

All have the { get; set; } at the end of them.

What I am wondering is if there is a way that I can clean up my code and even remove the need for { get; set; } while still making them public.

I know it's not a huge problem but I would like to try and clean up my code as much as possible.


Not nicely. It is the {get;set;} that is making them automatically implemented properties; without them they become fields. You really don't want public fields, so leave it alone.

Really, you aren't solving any problem here; leave it. This is normal (at least since automatically implemented properties were introduced), and the {get;set;} is not adding to the line count etc.


You can, but they will no longer public properties and instead would take on the form of public variables (which certainly isn't preferential and would be frowned upon, to be sure, so use at your own discretion):

public string abc;
public string def;

I'd say keep them as properties, auto-implemented properties are a God-send and your concern is unfounded.


If you remove { get; set; }, you will get a public field instead of a public property. Properties are often the preferred way of exposing simple members of your classes since they allow you to hide their implementation and change it without breaking dependent components.

If you have lots of code repetition, consider using base classes/inheritance for common properties (and methods) to clean up your code.


{ get; set; } means that you have setter and getter property (exactly telling those are auto-implemented properties) for a field. It's not a good idea to have public fields in the class and therefore you should encapsulate your fields with properties. So it's good that you have them.


If there are classes with the same properties you could extend one another.

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

class Student : Person
{
    public string StudentId { get; set; }
}

class ShopKeeper : Person
{
    public Shop Shop { get; }
}

In the example above Student and ShopKeeper would inherit the property Name, which means you only have to write it once.

You can't make the get and set methods any simpler.


:) you should have seen property with backing field like this below:

        private string _test;
        public string Test
        {
            get { return _test; }
            set { _test = value; }
        }

now that requires clean up :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号