The contextual keyword 'var' may only appear within a local variable declaration issues

bendr picture bendr · Jul 8, 2011 · Viewed 31.2k times · Source

I know what this means, and I have searched Google, and MSDN. But, how else am I going to get around this?

I have a function in my razor code inside the App_Code folder (using WebMatrix), and I get info from the database, do some calculations, then update the database with the new total.

But, how am I to pass variables to my method in the App_Code folder if it won't let me?

Here's what I've got:

EditQuantity.cshtml (root folder):

        try
        {
            Base baseClass;
            baseClass.CalculateTotalPriceInCart(Request.QueryString["PartNumber"], Request.QueryString["Description"], Session["OSFOID"], true);

            Response.Redirect("~/Cart.cshtml");
        }
        catch(Exception exmes)
        {
            message = exmes;
        }

And, Base.cs (inside App_Code folder):

using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using WebMatrix.Data;

/// <summary>
/// Summary description for ClassName
/// </summary>
public class Base
{   
    public void CalculateTotalPriceInCart(var PartNumber, var Description, var OrderId, bool IsBoxed)
    {
        var database = Database.Open("OSF");
        var query = "";
        var result = "";
        decimal price = 0.00M;

        if(IsBoxed)
        {
            // Select item.
            query = "SELECT Boxes, BoxPrice FROM Cart WHERE OrderId = '" + OrderId + "' AND PartNumber = '" + PartNumber + "' AND Description = '" + Description + "' AND IsBoxed = 1";
            result = database.Query(query);

            // Recalculate Price.
            foreach(var item in result)
            {
                price = result.Boxes * result.BoxPrice;
            }

            // Update item.
            query = "UPDATE Cart SET BoxPrice = '" + price + "' WHERE OrderId = '" + OrderId + "' AND PartNumber = '" + PartNumber + "' AND Description = '" + Description + "' AND IsBoxed = 1";
            database.Execute(query);
        }
    }
}

I've tried a few things to see if it'd work, but nope. I'm obviously doing it wrong, but this is how I do it in Desktop apps, I don't get why it'd be different here for WebPages, and how shold I go about doing this?

Thank you!

Answer

Amy picture Amy · Jul 8, 2011

You can't define method parameters with the var keyword because the compiler cannot determine the method signature at compile time.

public void CalculateTotalPriceInCart(
         string Description, 
         string PartNumber, 
         string OrderId, 
         bool IsBoxed)

In another comment you said it can't cast IEnumerable<dynamic> to a string. So declare the parameter properly! I don't know which it is.

public void CalculateTotalPriceInCart(
         IEnumerable<dynamic> Description, // for example
         string PartNumber, 
         string OrderId, 
         bool IsBoxed)