c# - Can I enforce that fields in a POCO are only ever set in a type initialiser? -



c# - Can I enforce that fields in a POCO are only ever set in a type initialiser? -

if have poco such this:

[poco] public class mypoco { public string firstname { get; set; } public string lastname { get; set; } public string address { get; set; } }

... , it's initialised this:

new mypoco { firstname = "joe", lastname="bloggs", address="123 abc st." }

can i, using cql in ndepend, ensure properties ever set using object initialiser above, , not separately.

i'm trying grab code this:

mypoco.firstname="john"; dosomething(mypoco);

... don't want people set properties on existing poco. understand can create setters private, don't passing in properties in constructor because end signature such mypoco(string, string, string) - making easier misalign parameters (easier using object initialiser syntax)

so, want grab using ndepend. here's start of cql query:

from f in justmycode.fields.where(f=> f.parenttype.hasattribute ("jetbrains.annotations.pocoattribute".allownomatch())) f.methodsassigningme [i'm stumped here]

it looks can analyse method setting property of poco, need go 1 step lower , examing code block see if it's in object initialiser block.

is possible?

i don't know whether can in cql, although if can't, might able roslyn.

however, might want consider using builder pattern instead:

var poco = new mypoco.builder { firstname = "joe", lastname="bloggs", address="123 abc st." }.build();

now poco can immutable, builder can have properties set wherever like.

heck, if you're fan of implicit conversions could have implicit conversion builder poco:

mypoco poco = new mypoco.builder { firstname = "joe", lastname="bloggs", address="123 abc st." };

while i'm tools verifying proper coding it's not possible design type avoid beingness misused start with, i'd prefer have idiot-proof api start :)

also note named arguments in c# 4, constructor version can made clear:

var poco = new mypoco(firstname: "joe", lastname: "bloggs", address: "123 abc st.");

but of course of study still allows people write without named arguments...

c# poco code-analysis cql ndepend

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

c# - Create a Notification Object (Email or Page) At Run Time -- Dependency Injection or Factory -

Set Up Of Common Name Of SSL Certificate To Protect Plesk Panel -