Thursday, 12 September 2013

How to use same instance name with multiple classes

How to use same instance name with multiple classes

I'm new to c# and I think I want to do this but maybe I don't and don't
know it!
I have a class called SyncJob. I want to be able to create an instance to
backup files from My Documents (just an example). Then I'd like to create
another instance of SyncJob to backup files in another folder. So, in
other words, I could have multiple instances of the same class in memory.
I'm declaring the object var first in my code so it is accessible to all
the methods below it.
My question is: while using the same instance name will create a new
instance in memory for the object, how can I manage these objects?
Meaning, if I want to set one of the properties how do I tell the compiler
which instance to apply the change to?
As I said in the beginning, maybe this is the wrong scheme for managing
multiple instances of the same class...maybe there is a better way.
Here is my prototype code:
Form1.cs
namespace Class_Demo
{
public partial class Form1 : Form
{
BMI patient; // public declarition
public Form1()
{
InitializeComponent();
}
private void btnCreateInstance1_Click(object sender, EventArgs e)
{
patient = new BMI("Instance 1 Created", 11); // call
overloaded with 2 arguments
displayInstanceName(patient);
}
private void displayInstanceName(BMI patient)
{
MessageBox.Show("Instance:"+patient.getName()+"\nwith
Age:"+patient.getAge());
}
private void btnCreateInstance2_Click(object sender, EventArgs e)
{
patient = new BMI("Instance 2 Created", 22); // call
overloaded with 2 arguments
displayInstanceName(patient);
}
private void btnSetNameToJohn_Click(object sender, EventArgs e)
{
// this is the issue: which instance is being set and how can
I control that?
// which instance of patient is being set?
patient.setName("John");
}
private void btnDisplayNameJohn_Click(object sender, EventArgs e)
{
// this is another issue: which instance is being displayed
and how can I control that?
// which instance of patient is being displayed?
displayInstanceName(patient);
}
}
}
Class file: namespace Class_Demo { class BMI { // Member variables public
string _newName { get; set; } public int _newAge { get; set; }
// Default Constructor
public BMI() // default constructor name must be same as class
name -- no void
{
_newName = "";
_newAge = 0;
}
// Overload constructor
public BMI(string name, int age)
{
_newName = name;
_newAge = age;
}
//Accessor methods/functions
public string getName()
{
return _newName;
}
public int getAge()
{
return _newAge;
}
public void setName(string name)
{
_newName = name;
}
}
}

No comments:

Post a Comment