properties - What is the correct way to create methods that change private fields in C#? -


i switched c# java , became familiar notion of property, seems common way of getting , setting field values.

so should if need update field values pretty often, not setting them totally new values? like, there field in class list, , need append elements it, while keeping rest of list unchanged. should go ahead , create method like

void append(point p) { } 

or there more elegant or civilized way of doing in c#?

there no single "correct" way of setting private fields through api. answer depends on functionality present users.

if let them access list<point> read-only collection can modify in way like, may present list read-only property:

public ilist<point> points {get;} = new list<point>(); 

if think approach gives users freedom, , prefer have tighter control on points appear on list, may want expose property accessing list ienumerable<point> , bunch of methods adding / removing / modifying points on list.

private ilist<point> points = new list<point>(); public ienumerable<point> points => points; public void addpoint(point p) {     // validate p before inserting on list,     ...     points.add(p); } 

note: code examples above use c# 6 syntax.


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -