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?

1
  • What is the problem if it works like a charm ? Commented Nov 4, 2015 at 13:26

1 Answer 1

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; }
}
Sign up to request clarification or add additional context in comments.

5 Comments

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
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 public string Something { get; set; } is very different from public string Something { get { return Something; } set { Something = value; } }
I get it now, I have never seen that before. Thanks for your answer
@Leze No problem! Always glad to help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.