0

I am changing some public field to private by providing corresponding public property.

for example:

public string Name;

is change to

private string _name;
public string Name
{
    get{ return _name;}
    set{ _name = value;}
}

However, what about the [XmlAttribute] attribute on the original public field? i.e. does

[XmlAttribute]
public string Name;

becomes:

[XmlAttribute]
private string _name;
public string Name
{
    get{ return _name;}
    set{ _name = value;}
}

or

private string _name;
[XmlAttribute]
public string Name
{
    get{ return _name;}
    set{ _name = value;}
}
Fan Jia
  • 117
  • 5

2 Answers2

6

second solution.

By the way, you don't need anymore (.net 3.0 and +) a private field, if you don't do anything special in getter or setter.

You can use auto-implemented properties.

[XmlAttribute]
public string Name {get;set;}
Raphaël Althaus
  • 57,325
  • 6
  • 81
  • 109
  • Thank you Raphael, the reason i do that is because the Sonar(code quality control) detects the public string Name; with the following rule: [link](https://github.com/spouliot/gendarme/wiki/Gendarme.Rules.Design.AvoidVisibleFieldsRule(2.10)) – Fan Jia Nov 01 '12 at 15:42
  • @IC_Weekend well... because the property is public, while the field is private. And default serialization can't work on private fields. See http://stackoverflow.com/questions/802711/serializing-private-member-data – Raphaël Althaus Nov 01 '12 at 15:44
  • @IC_Weekend yes, use public fields is not a good idea, but your Sonar will accept auto-implemented properties (if it doesn't, change it ;) ) – Raphaël Althaus Nov 01 '12 at 15:47
1

And instead of doing

private string _name;
public string Name
{
get{ return _name;}
set{ _name = value;}
}

why not do

public string Name { get; set; }

I think this was introduced in C# 3.0

Drew Holiday
  • 113
  • 4