Rani Radcliff
Rani Radcliff

Reputation: 5084

Set Value of String in Static Class

I am trying to set the value of a string in a static class from a button click on an .aspx page. I am not understanding why the value is always null.

Here is the static class code:

public static class XeroApiHelper
{
    private static ApplicationSettings _applicationSettings;
    public static string WebUrl { get; set; }

    static XeroApiHelper()
    {
        // Refer to README.md for details

        string callbackUrl = WebUrl + "/xero/xeroconnection.aspx";

The string I am trying to set is the WebUrl.

Here is the code in the click event:

protected void btnXeroConnect_Click(object sender, ImageClickEventArgs e)
{
    string weburl = Request.Url.GetLeftPart(UriPartial.Authority);
    XeroApiHelper.WebUrl = weburl;
    _user = XeroApiHelper.User();
    _authenticator = XeroApiHelper.MvcAuthenticator();
    var authorizeUrl = _authenticator.GetRequestTokenAuthorizeUrl(_user.Name);
    Response.Redirect(authorizeUrl);
}

Any assistance is greatly appreciated.

Upvotes: 2

Views: 2700

Answers (1)

MKR
MKR

Reputation: 20095

This because of static constructor. The constructor is called before any static member is referenced. That means constructor has been called before line XeroApiHelper.WebUrl = weburl; is execute. That sets null value in callbackUrl

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. A static constructor will run before an instance constructor. A type's static constructor is called when a static method assigned to an event or a delegate is invoked and not when it is assigned. If static field variable initializers are present in the class of the static constructor, they will be executed in the textual order in which they appear in the class declaration immediately prior to the execution of the static constructor.

Static constructors

Edited: to include possible solution

Move code from static constructor to set call of WebUrl as:

private static string _WebUrl;
public static string WebUrl
{
    get { return _WebUrl; }
    set
    {
        _WebUrl = value;
        string  callbackUrl = _WebUrl + "/xero/xeroconnection.aspx";
        // move rest of code from constructore here
    }
}

Upvotes: 1

Related Questions