Mura
Mura

Reputation: 71

About C# object scope

So I've created a class and instantiate an object in the main window. Then, when I'm trying to use that object in a button within the same window, I don't know how to indicate the context for this object. I know this is a very basic question, but I'm learning and haven't been able to figure it out just yet.

public MainWindow()
{
    InitializeComponent();
    DeltaMotor M2 = new DeltaMotor();
    M2.Card.Set8255();  
    M2.Stop();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    M2.Move(1); // this can't find M2 within the context
}

I know this is basic, but help will be greatly appreciated.

Upvotes: 0

Views: 265

Answers (4)

thekaveman
thekaveman

Reputation: 4399

As you've discovered, the M2 object is not in scope inside the click handler, because it is a local variable inside the MainWindow constructor.

You can make M2 an instance variable of the class, and access it from both methods, along the lines of:

private DeltaMotor M2;

public MainWindow()
{
    InitializeComponent();
    M2 = new DeltaMotor();
    M2.Card.Set8255();  
    M2.Stop();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    M2.Move(1);
}

Upvotes: 4

dornadigital
dornadigital

Reputation: 178

If you just want it to be accessible within this one class, then

private DeltaMotor M2;
public MainWindow()
{
    InitializeComponent();
    M2 = new DeltaMotor();
    M2.Card.Set8255();  
    M2.Stop();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    M2.Move(1); // this can't find M2 within the context
}

Will work quite nicely. For further learning, here's a Microsoft reference on variable and method scope: https://msdn.microsoft.com/en-us/library/ms973875.aspx

Which will be useful if you ever what to access M2 in another class. Hope that helps you get started!

Upvotes: 1

William Xifaras
William Xifaras

Reputation: 5312

You need to create an instance member of DeltaMotor at the class level.

private DeltaMotor _m2;

public MainWindow()
{
    InitializeComponent();
    _m2 = new DeltaMotor();
    _m2.Card.Set8255();  
    _m2.Stop();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    _m2.Move(1);
}

Upvotes: 0

Christos
Christos

Reputation: 53958

You could declare M2 as a class property:

private DeltaMotor M2 { get; set; }

public MainWindow()
{
    InitializeComponent();
    M2 = new DeltaMotor();
    M2.Card.Set8255();  
    M2.Stop();
}

and then access it from whatever method you want:

private void Button_Click(object sender, RoutedEventArgs e)
{
    M2.Move(1); 
}

Upvotes: 0

Related Questions