views:

673

answers:

8

the following syntax throws an compile time error like

Cannot convert type 'string' to 'int'

string name=(Session["name1"].ToString());
int i = (int)name;

whereas the code below compiles and executes successfully

string name=(Session["name1"].ToString());
int i = Convert.ToInt32(name);

I would like to know
1) why the compile time error occurs in first code
2) what's the difference between the 2 code snippets

A: 

1) because C# is type safe language and don't allow you to assign string to number
2) second case parses the string to new variable. In your case if the Session is ASP.NET session than you don't have to store string there and convert it back when retrieving

int iVal = 5;
Session[Name1] = 5;
int iVal1 = (int)Session[Name1];
ArsenMkrt
+8  A: 

(int)foo is simply a cast to the Int32 (int in C#) type. This is built into the CLR and requires that foo be a numeric variable (e.g. float, long, etc.) In this sense, it is very similar to a cast in C.

Convert.ToInt32 is designed to be a general conversion function. It does a good deal more than casting; namely, it can convert from any primitive type to a int (most notably, parsing a string). You can see the full list of overloads for this method here on MSDN.

Noldorin
A: 

Convert.ToInt32

    return int.Parse(value, CultureInfo.CurrentCulture);

but (int) is type cast, so (int)"2" will not work since you cannot cast string to int. but you can parse it like Convert.ToInt32 do

Trickster
A: 

The difference is that the first snippet is a cast and the second is a convert. Although, I think perhaps the compiler error is providing more confusion here because of the wording. Perhaps it would be better if it said "Cannot cast type 'string' to 'int'.

Joseph
+1  A: 

There is not a default cast from string to int in .NET. You can use int.Parse() or int.TryParse() to do this. Or, as you have done, you can use Convert.ToInt32().

However, in your example, why do a ToString() and then convert it back to an int at all? You could simply store the int in Session and retrieve it as follows:

int i = Session["name1"];
Jerry Bullard
+1  A: 

A string cannot be cast to an int through explicit casting. It must be converted using int.Parse.

Convert.ToInt32 basically wraps this method:

public static int ToInt32(string value)
{
    if (value == null)
    {
        return 0;
    }
    return int.Parse(value, CultureInfo.CurrentCulture);
}
Philip Wallace
+2  A: 

To quote from this Eric Lippert article:

Caste means two contradictory things: "check to see if this object really is of this type, throw if it is not" and "this object is not of the given type; find me an equivalent value that belongs to the given type".

So what you were trying to do in 1.) is assert that yes a String is an Int. But that assertion fails since String is not an int.

The reason 2.) succeeds is because Convert.ToInt32() parses the string and returns an int. It can still fail, for example:

Convert.ToInt32("Hello");

Would result in an Argument exception.

To sum up, converting from a String to an Int is a framework concern, not something implicit in the .Net type system.

ecoffey
A: 

(Casting) syntax only works between numeric and compatible native data types in the Common Type System. "Compatible" means inheritance types - i.e. base/derived classes, or implemented types - i.e. interfaces. Also casting works between disparate data types that have operator overloading applied.

The System.Convert class on the other hand contains logic to convert between disparate native data types that have a logical alternatives (including many of those handled by cast), although not a raw direct cast process.

Consider casting syntax and its behaviour a feature of the C# language with specifics to it, whereas the FCL System.Convert class is a part of the .NET framework and can be used for data type changes using any programming language.

John K