WebControl's constructor does not have correct attribute value

63 Views Asked by At

I want the constructor of my WebControl to be able to access the value of IsSpecial (from the HTML). However, it's always false. I assume that it's false in the constructor because it doesn't read the value until after the constructor method is over. Is there a way to have it so it knows the correct value of IsSpecial in the constructor?

C#:

[DefaultProperty("Text")]
[ToolboxData("<{0}:WebControlExample runat=server></{0}:WebControlExample>")]
public class WebControlExample: WebControl, INamingContainer
{
    private readonly int[] goodies;

    public WebControlExample()
    {
        if (this.isSpecial)
        {
            goodies = new int[24];
        }
        else
        {
            //always reaches here
            goodies = new int[48];
        }
    }

    private bool isSpecial= false;
    public bool IsSpecial
    {
        set
        {
            this.isSpecial= value;
        }
    }
}

HTML:

<xyz:WebControlExamplerunat="server" id="webControlExample" IsSpecial="true" />
2

There are 2 best solutions below

1
D Stanley On BEST ANSWER

This isn't a great solution, but if you have to have a readonly array, you could have two readonly arrays and wrap them in an accessor:

[DefaultProperty("Text")]
[ToolboxData("<{0}:WebControlExample runat=server></{0}:WebControlExample>")]
public class WebControlExample: WebControl, INamingContainer
{
    private readonly int[] goodies = new int[48];
    private readonly int[] goodiesSpecial = new int[24];

    private bool isSpecial= false;
    public bool IsSpecial
    {
        set
        {
            this.isSpecial= value;
        }
    }

    private int[] Goodies
    {
         get {return isSpecial ? goodiesSpecial : goodies;}
    }
}

But you haven't stated 1. Why you need two different-sized arrays or 2. What you're doing with them.

4
Rob On

The value entered in the markup for the IsSpecial property won't have been assigned to the property until after the constructor is run. Think about it,.. you're expecting code equivalent to the following:

WebControlExample webControlExample = null;
webControlExample.IsSpecial = true;
webControlExample = new WebControlExample();

What's actually happening (simplified!) is:

WebControlExample webControlExample = null;
webControlExample = new WebControlExample();
webControlExample.IsSpecial = true;

There is no way to affect this for the constructor, and you probably shouldn't be doing much of anything in the constructor for a WebControl anyway.