There is a simple class, I can not understand why I can not refer to the previously created object?

public partial class MainWindow : Window { public MyRepository MainRepo; public MainWindow() { MyRepository MainRepo = new MyRepository(); InitializeComponent(); DataContext = MainRepo; } private void AddMyButton_Click(object sender, RoutedEventArgs e) { .... MainRepo.AddMy(TempMy); } 

Why is MainRepo in the click handler null? When a program is started with tracing, it gets into the MainWindow method, the MainRepo object is created

  • In the above code, the possible reason for this is not visible, are you sure that there is a problem and it is not created by some other code that is not shown here? - Andrei NOP
  • one
    Because you never assign to this field. - Pavel Mayorov
  • @AndreyNOP look closer: everything is clearly visible here ... - Pavel Mayorov
  • 3
    Two different MainRepo are created, one public in the class and the other local in the MainWindow constructor. - Gennady P
  • one
    @PavelMayorov, ah, yes, the local variable is the same - Andrey NOP

1 answer 1

 MyRepository MainRepo = new MyRepository(); 

Because you specify an object type, MainRepo remains local to the MainWindow constructor.

just remove MyRepository:

 MainRepo = new MyRepository(); 

or save the reference in the object field (but it will be a strange solution):

 MyRepository MainRepo = new MyRepository(); this.MainRepo = MainRepo;