0

I have an strange comportement with my singleton class.

public class HttpCommunicator{
    public const int TYPEJSON = 1;

    private static HttpCommunicator;
    private bool TypeIsInit = false;

    public static HttpCommunicator Instance {
        get{
            if( instance == null ){
                instance = new HttpCommunication();
            }
            return instance;
        }
    }

    private HttpCommunicator(){}

    public int RequestType {get {return RequestType;} set{ this.RequestType = value; TypeIsInit = true;}
}

And later in another class i call this

HttpComminicator.Instance.RequestType = HttpCommunicator.TYPEJSON;

My app get stuck/freeze and my debugger don't show me any error. But if I change the get;set; method for this attribut to:

public int GetRequestType(){
    return RequestType;
}

public void SetRequestType(int value){
    RequestType = value;
    TypeIsInit = true;
}

everything works like a charm.

Anybody can explain me why I get this?

Leze
  • 739
  • 5
  • 24

1 Answers1

2

Check out your property:

public int RequestType
{
   get { return RequestType; }
   set { this.RequestType = value; TypeIsInit = true; }
}

You have a bunch of problems here.

What happens when you get that property? RequestType.get is going to execute, which in turn is going to return RequestType;. To return RequestType you must read RequestType, which will trigger RequestType.get and the loop will go on and on and on and on.

My point is that you're trying to return a property by returning said property, which will probably end up causing a StackOverflowException.

The same can be said about your set accessor.

To fix this, have private fields behind the scenes:

private int _requestType;
public int RequestType
{
     get { return _requestType; }
     set { _requestType = value; TypeIsInit = true; }
}
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
  • You are right, i made a mistake when i wrote this code, i just made a search about your write and found the correct answer in this post [5096926](http://stackoverflow.com/questions/5096926/what-is-the-get-set-syntax-in-c) – Leze Nov 04 '15 at 13:31
  • I notice that i use often the get; set; syntax and I never met this problem since today. I write this public string Something {get; set;} and later in code call Something = "Hello" and to get just Log.I('',Something); – Leze Nov 04 '15 at 13:34
  • @Leze `public string Something { get; set; }` is very different from `public string Something { get { return Something; } set { Something = value; } }` – Matias Cicero Nov 04 '15 at 13:35
  • I get it now, I have never seen that before. Thanks for your answer – Leze Nov 04 '15 at 13:36
  • @Leze No problem! Always glad to help! – Matias Cicero Nov 04 '15 at 13:37