tux007 tux007 - 16 days ago 5
C# Question

using an object in another class

here my example for my problem:

namespace test
{
public partial class MainWindow : Window
{

private Data theData= new Data();
private Handler theHandler = new Handler(theData);

public MainWindow()
{
InitializeComponent();
}
......

}

class Handler
{

Data theData;
public Handler(Data theDa)
{
theData = theDa;
}

//some funktions which are using theData

}

class Data
{
public Data()
{

}
public string a;
public string b;
}

}


I have a window class, with a instance of a class to do somethink (Handler) and a class to store data (Data).

I think the way I showed is a little bit quick and dirty. Can someone tell me how I'm able to use theData in my Handler class without using the constructor?

Answer

You have this 100% correct (besides having all the classes in one file!)

For Handler to act on an instance of Data it must be given it. There are other ways besides in the constructor (assigning a property, or a parameter to its methods) but if a given instance of Handler should only act on one instance of Data then your model is just fine.

The only other issue is that you have public fields in Data, which is considered bad practice; you should use properties instead (with PascalCase names).

The only other alternative I can think of is to have Handler instantiate Data if MainWindow doesn't care about the Data reference.

Comments