Getters, setters, and properties best practices. Java vs. C# -
i'm taking c# class right , i'm trying find out best way of doing things. come java background , i'm familiar java best-practices; i'm c# novice!
in java if have private property, this;
private string name; public void setname(string name) { this.name = name; } public string getname() { return this.name; }
in c#, see there many ways of doing this.
i can java:
private string name; public void setname(string name) { this.name = name; } public string getname() { return this.name; }
or can way:
private string name; public string name { { return name; } set { name = value; } }
or:
public string name { get; set; }
which 1 should use, , caveats or subtleties involved each approach? when creating classes, following general best-practices know java (especially reading effective java). example, favoring immutability (providing setters when necessary). i'm curious see how these practices fit in various ways of providing setters , getters in c#; essentially, how translate best-practices java world c#?
edit
i posting comment jon skeet's answer got long:
what non-trivial property (i.e., significant processing , validation perhaps)? still expose via public property logic encapsulated in get
, set
? why would/should on having dedicated setter , getter methods (with associated processing , validation logic).
pre-c# 6
i'd use last of these, trivial property. note i'd call public property both getters , setters public.
immutability bit of pain automatically implemented properties - can't write auto-property has getter; closest can come is:
public string foo { get; private set; }
which isn't really immutable... immutable outside class. may wish use real read-only property instead:
private readonly string foo; public string foo { { return foo; } }
you don't want write getname()
, setname()
. in some cases makes sense write get/set methods rather using properties, particularly if expensive , wish emphasize that. however, you'd want follow .net naming convention of pascalcase methods, , wouldn't want trivial property implemented normal methods anyway - property more idiomatic here.
c# 6
hooray, have proper read-only automatically implemented properties:
// can assigned within constructor public string foo { get; }
likewise read-only properties do need work, can use member-bodied properties:
public double area => height * width;
Comments
Post a Comment