access and set variables in a class from another class

All we need is an easy explanation of the problem, so here it is.

i’v a shopping_cart.aspx.cs file & also have a class file spcart.cs,

shopping_cart.aspx.cs

public partial class Ui_ShoppingCart : System.Web.UI.Page
{
    public int tax = 0;   
    public int subtotal = 0;
    public int granttotal = 0;  

    protected void Page_Load(object sender, EventArgs e)
         {
             -------------------------/////some code
         }
   --------------------------------/////some code
}

spcart.cs

public class Spcart
    {     
        public void updatecart(int pid,int qty)
         {
             ---------/////some code
         }
    }

now i want to set some values in class Ui_ShoppingCart variables tax, subtoal & granttotals from class Spcart, so i’d tried–>

Ui_ShoppingCart.tax

but it didnt worked………
is there any other way to set these variables ???
can anyone help me about this???

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I think it should be the other way round

protected void Page_Load(object sender, EventArgs e)
{
   SpCart cart = new SpCart();
   cart.updateCart(124, 4);

   tax = cart.getComputedTax();
   subTotal = cart.getSubTotal();
   ...
}

The idea is those variables should independent of your SpCart code.

public class Spcart
{     
     public void updatecart(int pid,int qty)
     {
         ---------/////some code
     }

     public int getComputedTax()
     {
       //can compute tax here
       int tax = whatever;
       return tax;
     }
}

The computation logics can still be separated into some other class

Method 2

I think you are trying to access “tax” property declared in “Ui_ShoppingCart” from “Spcart” class. It is not possible to do it. Instead you have to pass them as additional parameters to updatecart method.

Spcart cart = new Spcart();
cart.updatecart(pid,qty,tax);

Or if tax is used in other methods of the “spcart” class, initialize it in the contructor.

public class Spcart
{     
 private int _tax = 0;
 public Spcart(int tax)
 {
   _tax = tax;
 }
 public void updatecart(int pid,int qty)
 {
    int amount = qty + _tax;
 }
}

And call using

Spcart cart = new Spcart(tax);
cart.updatecart(pid,qty);

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply