Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# does var have a strong type?

As at the link: http://msdn.microsoft.com/en-us/library/bb383973.aspx

...An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type...

But I have such piece of code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["user"] == null) Response.Redirect("Default.aspx");

        StringBuilder sb = new StringBuilder();

        foreach (var item in Session)
        {
            sb.Append("Session Parameter: [");
            sb.Append(item);
            sb.Append("]<p />Guid Value: [");
            sb.Append(Session[item] + "]");
        }

        Response.Write(sb.ToString());
    }

I'm getting such error in Visual Studio:

Argument 1: cannot convert from 'object' to 'string' for the line:

 sb.Append(Session[item] + "]");

But item is identifying at runtime as a string type as I looked in the debugger.

When I have read about var at msdn/in books I thought that var doesn't relate to RTTI-stuff. Compilers just changes the variable with this implicitly type on explicitly type like string, int etc at compile time.

Why did I catch such error?

like image 856
Secret Avatar asked Dec 03 '22 00:12

Secret


1 Answers

A var declaration in C# is strongly typed but in this case you are dealing with a non-generic collection type in the value Session. This causes C# to choose object for the type of item and hence you get a later error trying to use item in a position that requires a string.

For non-generic collections you need to still explicitly type the iterator variable in a foreach block

foreach(string item in Session) { 
  ...
}
like image 134
JaredPar Avatar answered Dec 26 '22 20:12

JaredPar