access and set variables in a class from another class

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???

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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);


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x