'How to use one array in multiple classes?

I am definitely doing something wrong here. I created a program and a class. Here is the program code I have written so far:

public class CashRegisterViewModel: Cash
{ 
    static void Main(string[] args)
    {
       double amountdue = 100;
        double amountpaid = 1650;
        Cash register = new Cash();


        for( double i = amountpaid; i < 0; i--)
        {
            register.Cash ;
        }
    }
}

And here is the code I have written for the Cash class, where I control the "Cash Register" part of the code:

static void Register()
    {
        double[] cashmoney = { 100, 50, 230, 10, 5, 2, 1 };
        Array.Sort(cashmoney);
        Array.Reverse(cashmoney);

    }

    int index = cashmoney.Length();

So far so good? Not quite. Despite it being only a few lines of code, I have encountered several problems already:

  • I can't use the Array.Length() function in the cash class
  • I seemingly can't call the array in the program, since it "Doesn't exist"

And that's it, for now. I am pretty new to Csharp, so I think I missed some vital information while creating the class.



Solution 1:[1]

You are calling cashmoney.Length() outside of the scope where you declared the array. Also Length is a property so you can't call it like a method. You are declaring the array in the Register method, so the variable is only available there.

Have a look here, to learn more about scopes.

You could create a property in the Cash class called Cashmoney, like this:

public double[] Cashmoney {get; set;}

That way you can access that property from outside. Learn more about properties here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1