ASP.NET C#: Will <%:myInt%> result in boxing?

112 Views Asked by At

Passing a value type as type object to a function in C# and boxing occurs.

In ASP.NET we have shorthand's for Response.Write(..) and Response.Write(Server.HtmlEncode(..)) respectively, <%= and <%:

Response.Write(..) exist with overloads for char, string and object - I therefor assume that this code will result in Response.Write(object) being called and the int being boxed:

<%int myInt = 3;%>
<%=myInt%>

while as i understand it this version will not result in boxing:

<%=myInt.ToString()%>

(Correct me if I'm wrong here)

But what about <%:?

Server.HtmlEncode() only takes a string as parameter and can not be called with a type of object. So what is happening in this situation:

<%:nyInt%>

Will the webform view engine "compile" it to something like

Response.Write(Server.HtmlEncode(myInt.ToString))

a "magic no boxing" scenario?

Update

Following Joe’s example shows that <%:nyInt%> is translated to

@__w.Write(System.Web.HttpUtility.HtmlEncode(myInt));

System.Web.HttpUtility.HtmlEncode has an overload for object - this means that the conclusion is that <%: myInt%> cause boxing - regardless of whether it cause a performance penalty or not :-)

1

There are 1 best solutions below

1
On

If you want to know what the generated source code looks like, an easy way is to add some script to your page with a deliberate compile-time error, e.g.

    <script runat="server"> 
        deliberate error here
    </script>

The error page displayed when the compile fails includes a link to view the complete generated source code, which will answer your questions above.

As for boxing, you shouldn't be concerned.

Repeatedly boxing and unboxing can have a performance penalty, e.g.:

object myInt;
...
for (i=0; i<aVeryLargeNumber; i++)
{
    ...
    myInt = ((int)myInt)+1;
    ...
}

But in your example above, there is no reason to be concerned.