1

I saw in a blog that you can cast from string to int and something even better dealing with possible null values using (int?). See blog here

However, when I try to do it, visual studio complains saying Cannot implicitly convert type 'int' to 'string'.

Is it really possible? Or am I doing something wrong?

Amra
  • 24,780
  • 27
  • 82
  • 92
  • 4
    There's no bit in that article that tries to do that, as far as I can see. Can you point out the part that you think appears to do so? In any case, you can't "cast" from `string` to `int`. Look up `int.Parse`, `int.TryParse` and `Convert.ToInt32`. On another note, `int` is just an alias for `System.Int32`. – Ani Nov 25 '10 at 17:03
  • After the second screen shoot of the employees table shown in IE – Amra Nov 25 '10 at 17:04
  • 3
    XElement has defined explicit conversion to int?, int, double?, double, decimal?, decimal, Guid, Guid? etc... – Lex Lavnikov Nov 25 '10 at 17:07
  • He's casting an object as an int there. The data element coming out of the database is of unknown type, so you don't have to cast to string or int when you use it as a string, but if you want to use it as an int, you have to cast it. – Kendrick Nov 25 '10 at 17:08
  • @LexL:Thank you for the explanation, I can understand now why he is doing it. – Amra Nov 25 '10 at 17:12

13 Answers13

2

Use int.Parse() or, better yet, int.TryParse()

int someInt;
if(int.TryParse(aString, out someInt)
{
    // work with the int
}
else
{
    // handle error
}

The difference is, int.Parse() throws an exception if the string isn't a valid integer. int.TryParse() returns true and sets its out parameter to the result if it's a valid integer, otherwise it returns false and the out parameter's value is undefined.

Sean U
  • 6,730
  • 1
  • 24
  • 43
  • Thanks for the explanation for TryParse it really helped me to understand better the TryParse + 1 for that, because it does not explain what I was doing wrong, I will not select this one as answer. – Amra Nov 25 '10 at 17:39
2

The article discusses the null coalesce operator (??), not nullables (int?, bool? etc).

This is a mechanism to ensure the first non null value can be assigned to a variable.

From MSDN:

is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.

Both sides of the operator should be of the same type or have an implicit conversion between them in order to use it.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • Thanks for your answer + 1, but it is a bit advance answer for me to understand fully. – Amra Nov 25 '10 at 17:41
2

In the article mentioned an XElement is casted to an int (or int?), because XElement implements explicit conversion operators.

You cannot cast a string that way. You would have to use something like int.Parse or int.TryParse for that.

TToni
  • 9,145
  • 1
  • 28
  • 42
2

What you're trying to do can't be done. But, you can use extension method, so you'd end up using it like this:

int? myInt = "123".ToNullableInt();

The definition of the extension would be:

public static class Extensions
{
   public static int? ToNullableInt(this string arg)
   {
       int result;
       if (int.TryParse(arg, out result))
       {
           return result;
       }
       return null;
    }
}
veljkoz
  • 8,384
  • 8
  • 55
  • 91
1

You can't cast from string to int, but you can do a conversion. So you might want to do this:

int value = Convert.ToInt32("1234");

The blog article you link to does not talk about casting string to int. Rather, it talks about using the null coalescing operator. One way this can be used to deal with converting strings, would be to make a convert method returning int?, then using null coalescing operator to provide the default value of choice. Then you would be able to say:

int value = SafeConvert.ToInt32(stringValue) ?? 1; // Assigned 1 if conversion fails.

This is one possible implementation of the SafeConvert.ToInt32 method:

public static int? ToInt32(string value)
{
    int n;
    if(!int.TryParse(value,out n))
        return null;
    return n;
}
driis
  • 161,458
  • 45
  • 265
  • 341
1

Casting string to integer is not possible. However, int.Parse(string) and Convert.ToInt32(object) could help.

You can cast null values of any type (as long as its boxed) to Nullable... In this case you'll always get null.

Lex Lavnikov
  • 1,239
  • 9
  • 18
0

Lets have a brief look at it with sample code

int x = int.parse("546")

will produce output

x = 546

but this

x = int.parse("546.0")

will give error. For this you have to do double

x = convert.todouble("546.0")

which will give

x = 546.0 

and convert.toint32(x) will produce 546. So crux is that string containing literal of double akin can't be directly converted to double primitive type.

tchrikch
  • 2,428
  • 1
  • 23
  • 43
0

Did you mean Int32.Parse and Int32.TryParse?

alpha-mouse
  • 4,953
  • 24
  • 36
0
 int number =   int.Parse("123");
Ali Tarhini
  • 5,278
  • 6
  • 41
  • 66
0

Nowhere in that article did I see him cast a String as an int. If you know the string is an int, you can use Int32.Parse("123"), and if you aren't sure, you can use Int32.TryParse("123x",out intValue), which will return false if the string is not an int (as opposed to throwing an error)

Kendrick
  • 3,747
  • 1
  • 23
  • 41
0

Can't you just use the int.TryParse method?

string stringToCast = "1";
int result;
int.TryParse(stringToCast, out result);
Breandán
  • 1,855
  • 22
  • 34
0

Yuo should be able to cast using int.Parse or int.TryParse. If you're just doing a simple (int) myvar then it will give you an error.

Jeff Hornby
  • 12,948
  • 4
  • 40
  • 61
0

Casting from string to int is not possible in C#. You can you int.Parse(somestring) to do that.

What that article is talking about is that this:

string a = somestring ?? "";

is a short way to do this:

string a;
if (somestring == null)
{
    a = somestring;
}
else
{
    a = "";
}
gligoran
  • 3,267
  • 3
  • 32
  • 47