integer constants used with string constants

E

Eric Newton

Given the following: [VB]
-----------------------
Option Strict On
Public Const ID_LIST_LIMIT as integer = 2000

<WebMethod(Description:="idList cannot have more than " & ID_LIST_LIMIT & "
items.")> _
Public Function SomeFunction(byval idList() as Integer) as Boolean()
if idList.Length = 0 then exit sub
if idList.Length > ID_LIST_LIMIT then throw new
ArgumentOutOfRangeException("idList has more than " & ID_LIST_LIMIT & "
items. Please revise your request."

End Function
----------------------

Here's the problem: the ID_LIST_LIMIT coersion to string works fine for the
ArgumentException constructor because the language seems to defer the
coersion to runtime. However, the coersion fails for the webmethod
constructor because the compiler apparently refuses to coerce the integer to
a string for the purpose of the webmethod attribute's construction.

The only way i've found to alleviate the "problem" is to declare a string
constant and hope that the two will always be the same... most likely... but
not 100% guaranteed.

To the framework compiler builders: Any plans to change this? Since you can
only use value types in attributes anyways, couldnt the compiler invoke a
integer.tostring() itself in the context of the constructor? Not
afterwards, but actually during compilation, so that if an overflow WOULD
occur then it DOES occur...
 
E

Eric Newton

Technically speaking, you are correct, however strings are immutable in the
framework and hence are treated as value types.
 
J

Jon Skeet [C# MVP]

Eric Newton said:
Technically speaking, you are correct, however strings are immutable in the
framework and hence are treated as value types.

No, there's a big difference between "reference type which is
immutable" and "value type". For instance, as string is a reference
type I'm guaranteed that for:

string a = "some long string";
string b=a;
string c=a;
string d=a;
string e=a;

the size of each of the variables is only the size of a reference. If
string were a value type, it could be much larger.

Similarly, when treating a string as just "object" no boxing occurs,
which makes a big difference in performance.

In my view it's worth keeping the two concepts well and truly distinct.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top