-2

Hello I have a WPF/C# application with 2 windows. I am trying to access a

public int myInt;

in my MainWindow from my OtherWindow:

MainWindow.myInt =3;

intellisense wont even allow me to access the variable.

Could someone please help?

H.B.
  • 166,899
  • 29
  • 327
  • 400
Laserbeak43
  • 595
  • 2
  • 8
  • 21
  • 2
    possible duplicate of [C#: Accessing form members from another class](http://stackoverflow.com/questions/717264/c-accessing-form-members-from-another-class) – Jesse C. Slicer Sep 19 '12 at 21:39
  • 4
    You should probably learn [some basics](http://msdn.microsoft.com/en-us/library/ms173109.aspx) about object oriented programming. – H.B. Sep 19 '12 at 21:39
  • Take a look at [MVVM](http://www.codeproject.com/Articles/81484/A-Practical-Quick-start-Tutorial-on-MVVM-in-WPF). – NominSim Sep 19 '12 at 21:39

2 Answers2

4

You need to declare it as static as you don't access it via an instance, but via class name. That said, it is usually not considered good design to expose fields publicly.

Zdeslav Vojkovic
  • 14,391
  • 32
  • 45
  • i see. I guess this is off-topic, but even thought that's preached often, not making fields public, i've never seen an example showing my why. – Laserbeak43 Sep 19 '12 at 21:55
  • @Laserbeak43: There should be a very popular question about this here on SO somewhere... – H.B. Sep 19 '12 at 22:04
4

You either need to have an object:

MainWindow mw = new MainWindow();
mw.myInt = 3 

Or you need to make rour field static

public static int myInt;

and call it like your are already doing:

MainWindow.myInt =3;
JSBach
  • 4,679
  • 8
  • 51
  • 98