Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

c# - How to avoid property recursion

This hit me recently on a project I was working on. Most people are familiar with property recursion:

public int Test 
{
   get { return this.test; }
   set { this.Test = value; }
}
private int test;

You accidentally put an upper-case T in this setter, and you've opened yourself up to a StackoverflowException. What's worse is if you've not defined it, often visual studio will auto-correct the casing for you to the invalid state.

I did something similar however in a constructor recently:

public TestClass(int test)
{
    this.Test = Test;
}

Unfortunately here you don't get a StackOverflowException, now you've got a programming error. In my case this value was passed to a WebService that instead used a default value (which wasn't 0) which caused me to miss the fact I had incorrectly assigned it. Integration tests all passed because this service didn't say

"Hey you forgot this really important field!"

What steps can I take to avoid this sort of behaviour? I've always been advised against defining variables like the following, and I don't like them personally, but I can't think of any other options:

private int _test;
private int mTest;

EDIT

Reasons that the underscore or m prefix are undesirable normally that I can think of are:

  • Readability
  • Slightly more difficult to scroll through members if you're inheriting from 3rd party classes as you get a mix of styles.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Best way is to use "Auto implemented properties" here.

public int Test { get; set; }

If not possible to use "Auto implemented properties" for some reason use _ prefix(I don't prefer though).

If you also don't prefer to use some prefixes, then you have other option. You don't have to write the property code by hand. Let the IDE do it for you; that way you can avoid careless mistakes. (I don't know how I missed this in original answer)

Just type

private int test;

Select the field, Right click Refactor->Encapsulate Field. IDE will generate property snippet for you as below.

public int Test
{
    get { return test; }
    set { test = value; }
}

You don't need to bother clicking the context menu. If you prefer keyboard, shortcut is Ctrl + R + E.

Or get a Resharper, It will point your silly mistake immediately.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...