Question about casting datatypes

  • Thread starter valmir cinquini
  • Start date
V

valmir cinquini

hy = new System.Web.UI.WebControls.HyperLink();

Why this doesn't work?

if(something == true)
hy.NavigateUrl = "email.aspx?id=" + (string) p+1; ****



but this works correctly?

if(something == true)
hy.NavigateUrl = "email.aspx?id=" + Convert.ToString(p+1);

**** this way I got the following error:
Cannot convert type 'int' to 'string'

Why? (string) shouldn't cast p+1 result to a string?

TIA
 
J

J

Cast and Convert.ToString are 2 different concepts. Cast is not a
conversion routine.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

It's very simple,
(string)p + 1 means:

1)- treat p as string
2)- to the result of the above operation add the numeric value 1

Now this will ALWAYS FAIL because:
if p is numeric 1) will give error, as you cannot cast a numeric value to
string.
if p is convertible to string, then the error will be in 2) as 1 is numeric
and you cannot sum a numeric and a string value

The only way to do this is using convertion. now there is two possible ways
of doing so:
1) Convert.ToString( p + 1)
2- (p+1).ToString()


I would STRONGLY recommend 1 as it's clearer.

Hope this help,
 
V

valmir cinquini

J said:
Cast and Convert.ToString are 2 different concepts. Cast is not a
conversion routine.

Ok. I understand it, but p is an integer variable. Why can't I convert
it in a string using an cast operation?

Is it because I'm trying concatenate the convertion result with the
string "email.aspx?id="?

p originates from this line below:

int p = int.Parse(idNews);
 
J

Jon Skeet [C# MVP]

valmir cinquini said:
Ok. I understand it, but p is an integer variable. Why can't I convert
it in a string using an cast operation?

Because an integer just isn't a string, and there's no explicit
conversion *operator* from string to integer. Casts are there either to
tell the compiler to insert a runtime check that a reference to (say)
Object is really a reference to a String, or to tell it to invoke an
explicit conversion operator from one type to another.
Is it because I'm trying concatenate the convertion result with the
string "email.aspx?id="?

No.
 
V

valmir cinquini

John and Ignacio

Thanks for the explanations, they clear this up for me.

I learned C for DOS too many years ago and after that I always
developed in VB6. Since I'm living this .Net world, sometimes I've
caugh myself thinking as if I was 20 year old...good times, good
times...

For short, I cannot cast int to string because int is a native
datatype and string is a Object. Or not? Am I still wrong?
 

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