0

I know from the title you would say it's a duplicate, but...

So, I have created my class and made some objects (of class Masina) in MainWindow class constructor:

public class MainWindow
{ // example
     private Masina[] _masina = new Masina[10];
     _masina[0].Load(1, 'x');   // works
     SomeFunction(_masina);
}

When I use this class functions in Constructor it works fine, but when I try to use some function and pass this argue like this:

public static void SomeFunction(Masina[] masina) 
    {
        for (int i = 0; i < 10; i++)
            try
            {
                masina[i].Load(i, 'x');
            }
            catch
            {
            }
    }

then SomeFunction takes this argue as not referenced. ref don't work for me!

Can anyone help me to solve ?

armandasalmd
  • 169
  • 3
  • 10
  • 4
    What is the expected behavior and what do you see? "works" and "don't work" are not really helpful problem descriptions. – germi Apr 25 '16 at 09:34
  • What do you mean by ref "not working" what error do you get? Also are these two code snippets in the same file, if not is once referencing the other or are they in the same namspace? – Alfie Goodacre Apr 25 '16 at 09:34
  • 1
    This `private Masina[] _masina = new Masina[10]; _masina[0].Load(1, 'x');` should not work, since the array does not contain references to instances. – Maarten Apr 25 '16 at 09:35
  • 3
    Can you provide a _working_ example? Your first code snippet won't even compile as you try to call `_masina[0].Load` outside any method. And I'm sure that it won't work in a constructor, because you don't set `_masina[0]` to any instance, so it' s `null`: look at this: http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it?s=1|17.7204 – René Vogt Apr 25 '16 at 09:36

1 Answers1

1

Probably you want to initialize the Masina[] array in the constructor, like this:

public class MainWindow {
  // Declaraion is OK, calling method _masina[0].Load(1, 'x') - is not
  private Masina[] _masina = new Masina[10];

  // constructor is the place you're supposed to put complex initialization to
  public MainWindow() {
    // You can call the method in the constructor
    SomeFunction(_masina);
  }

  public static void SomeFunction(Masina[] masina) {
    // validate arguments in the public methods
    if (null == masina)
      throw new ArgumentNullException("masina");

    // do not use magic numbers (10), but actual parameters (masina.Length)
    for (int i = 0; i < masina.Length; ++i)
      masina[i].Load(i, 'x');

    // hiding all exceptions - catch {} - is very bad idea
  }
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215