How to use composition

Hey guys, i’m working in one project with web services. That’s only a CRUD but in this scenario I want to apply it with more than one table. So, in my create method I need to add more than one object to trigger it. I looked for the appropiate in my book and I found composition. That’s it’s but i don’t found anything in the C# documentation to do that. That’s why I’m here.

 private void btnNew_Click(object sender, EventArgs e)
            Client objC = new Client();
            objC.ide_cli = lblCod.Text;
            objC.nom_cli = txtName.Text;
            objC.pat_cli = txtLastNa1.Text;
            objC.mat_cli = txtLastNa2.Text;
            objC.dni_cli = txtId.Text;
            objC.dir_cli = txtAdd.Text;
            objC.fon_cli = txtTel.Text;
            Location objL = new Location();
            loc.region = txtRegion.Text
           /*How put objL inside objC to run my stored procedure in my db 
            then add the data in their tables*/

I’m programming my project in .NET Framework 4.7.2

Well most composition situations involve one of two methods for getting an object inside of another so that it can be used.

  1. Dependency injection - This is simply a fancy phrase to say pass the object into the constructor of container object saying that container object needs this object to function. In other words, you create something like…
Client objC = new Client(objL);  // <-- Here we are saying that client needs objL

In the constructor code of Client we can then take in the parameter and set it to a private member variable and work with it in our class.

  1. Create a setter method - Sometimes the first method doesn’t work because the class can’t take a parameter in from the constructor or that you simply don’t want to do that. With this method you add in a private member variable, then create a setter method that takes the objL object as a parameter. That setter method then of course sets the private variable and again you can use it in the container (for you Client object objC)

The idea of composition is a programming architectural idea and is not specific to any programming language. So it can be implemented in many languages with just different syntax. But what composition sounds just like what you need and you just needed to know a couple ways to implement it. I hope this information helps you out!

P.S. If Client is not a class you created and cannot modify, what you can also do is inherit from Client and then use something like the setter method on that inherited child class.