The problem is when you type "1" in the designer, it is assuming that "1" is
a string. Therefore, the Tag property does not hold a number, but an
instance of System.String. So in fact Tag actually contains a pointer to a
string "1" somewhere.
System.String cannot be directly cast to an int. Even if it COULD it
wouldn't work in this case.
The reason is due to boxing/unboxing--casting an Object to int will ONLY
work when that Object actually contains a boxed int.
For example, you can do this:
int a = 5;
short b = a;
And you can do this:
int a = 5;
object o = a;
int b = (int)o;
But you cannot do this:
int a = 5;
object o = a;
short b = (short)o;
To make the above code work, you would have to change it to:
int a = 5;
object o = a;
short b = (short)(int)o;
Or
int a = 5;
object o = a;
short b = Convert.ToInt16(o);
The Covnert class handles the casting and unboxing for you, as well as
conversions from strings to numbers (at the expense of
performance--especially if you already know the datatype of the boxed
value).
If you REALLY need to store an int directly in the Tag, you need to modify
the code that the Form designer generated for you. Somewhere in
InitializeComponent() you will see a line like this:
label.Tag = "1";
Which you could change to:
label.Tag = 1;
However, the designer will probably just change it back first chance it
gets. You could also set the value elsewhere (in the Form constructor for
example).
But both of these methods would defeat the purpose of the designer.
Incidentally, one could write a component similar to the ToolTipProvider
that added an IntTag to every control, but I don't think it's worth the
trouble.
I think the best solution is Convert.ToInt32().
However, if you're worried about performance, then:
Int32.Parse((string)label.Tag)
might run a bit faster....but you still have a string-to-int conversion
which isn't all that fast (relatively) to begin with.
Enough babbling on my part though.
--Matthew W. Jackson
"C# Learner" <cs****@learner.here> wrote in message
news:ud********************************@4ax.com...
C# Learner <cs****@learner.here> wrote:
<snip>
In that
case, wouldn't it just be holding 0x01?
I meant, "For example, if the Tag property is set to 1 at design-time,
wouldn't it just be holding 0x01?"
<snip>