passing class to another class

  • Thread starter Thread starter glenn
  • Start date Start date
G

glenn

I have a customer class that contains all of my fields and properties
related to a single customer. I then have a dataaccess class that knows how
to read and write a customer class to and from the database.

However, I want to have my customer class be the one that actually calls
the data access class and have it pass itself as a reference to the data
access class. This would allow the data access class to just write the info
in the class to the database, or to fill the class with data from a query
saving the customer class from having to receive info and then parse it back
into its proper places.

Can anyone tell me how this could be done?

Thanks,

glenn
 
Use the this keyword. For eg

class Customer
{
...
private void WriteData(DataManager d)
{
d.Write(this);
}
}

class DataManager
{
public void Write(Customer c)
{
// Write out data
}
}

Regards
Senthil
 
I tried to do that but the problem is the "this" keyword is a readonly
handle and you can't pass it as a ref. And therefore you can't fill it with
data from the other class when you are done...

Thanks,

glenn
 
Thanks for the idea. That seems to work. I define an object type set equal
to the "this" item, pass it through as a reference and then recast it as my
main class inside the other class. Haven't tested yet but its all
compiling... Hopefully it will work...

Thanks,

glenn
 
Can't you use the constructor to do the job then?

void CreateObject()
{
MyClass c = data.CreateObject();
}

class Data
{
MyClass CreateObject() { return new MyClass(); }
}

If you really want to change this, you can use a struct instead of a
class.
 
I tried to do that but the problem is the "this" keyword is a readonly
handle and you can't pass it as a ref. And therefore you can't fill it with
data from the other class when you are done...

Not using the ref qualifier does not prevent you from changing the contents
of an object parameter, it just prevents you from changing the address of
the object being passed in.

Try the following code, you will find that the FillThing method changes the
Name field.

/////////////////////////
public class Thing
{
public string Name;

public void FillMe()
{
Data.FillThing(this);
}
}

public class Data
{
public static void FillThing(Thing obj)
{
obj.Name = "Joanna";
}
}

class Class
{
[STAThread]
static void Main(string[] args)
{
Thing t = new Thing();
Console.WriteLine(t.Name);
t.FillMe();
Console.WriteLine(t.Name);
Console.ReadLine();
}
}
/////////////////////////

Joanna
 
Back
Top