开发者

Using .NET magic get set are best practices?

开发者 https://www.devze.com 2023-04-06 08:56 出处:网络
It is okay to use this in code (in the mvc 3 context or any other context) : protected String test { get; set; }

It is okay to use this in code (in the mvc 3 context or any other context) :

protected String test { get; set; }

Would like to hear why it is and why it is n开发者_如何学JAVAot if you have any of those answers.

Thanks.


It is simply a convenience.

All it does is remove boiler plate code for you, since it really is equivalent to

private String _test;
protected String test{
 get{
  return _test;
 }
 set{
  _test = value;
 }
}

So, when that's all it is, use magic get set. When you need to do something more funky, then implement the getsetters.

For example, in MVC, I often want to use Enums for my properties, but it is not supported by CodeFirst. So, I do this:

[Column("Type")]
public byte DBType;
public MyCustomEnum Type{
 get{
  return (MyCustomEnum)DBType;
 }
 set{
  DBType = (byte)value;
 }
}

And this populates my database as expected.


It is completely okay. It is the same thing as using a full property with manual backing, just that its backing is auto-generated by the compiler. If you need greater control over the implementation of get-set, use the verbose syntax by all means, but if you just need simple properties (for VM properties in MVC for example) use this syntax, as it makes the code much more readable and direct to the point.

0

精彩评论

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