0

I have following scenarios in my code and want to understand Aggregation, Composition, Association relation between the classes.

1)

class A : IDisposable
{
    private B objB;

    public A(B )
    {
        objB = new B();
    }

    public void Dispose()
    {
        objB.Dispose();
    }
}

2)

class A : IDisposable
    {
        private B objB;

        public A(B objB)
        {
            this.objB = objB;
        }

        public void Dispose()
        {

        }
    }

3)

class A : IDisposable
    {
        private B objB;

        public A()
        {

        }

        public void Sample()
        {
            objB = new B();
        }

        public void Dispose()
        {
            if (objB != null)
            {
                objB.Dispose();
            }
        }
    }

4)

class A : IDisposable
    {

        public A()
        {

        }

        public void Sample()
        {
            using (B objB = new B())
            {
                //Do some operation
            }

        }

        public void Dispose()
        {

        }
    }
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
ratty
  • 13,216
  • 29
  • 75
  • 108

1 Answers1

2

In concise

Association - There are two objects that know about each other, but they can't affect to each other's lifetime.

Composition - There are two classes: A and B.Object of the class A contains a class B object, and can't logically be created without class B.

Aggregation - is a variant of the "has a" association relationship; aggregation is more specific than association. It is an association that represents a part-whole or part-of relationship.

In your examples, 1, and 3 are Compositions, because they contain class B object.Example 4 is Association, because it only knows about class B and only uses it's object as a local variable.Example 2 is and Aggregation.

enter image description here

For more you can read in wiki https://en.wikipedia.org/wiki/Class_diagram

EDITED:

Difference between Composition and Aggregation.

Composition relationship: When attempting to represent real-world whole-part relationships, e.g. an engine is a part of a car.
Aggregation relationship: When representing a software or database relationship, e.g. car model engine ENG01 is part of a car model CM01, as the engine, ENG01, may be also part of a different car model.

In your example 1, your create an object of class B in your class A.Based on your code you can't give the created object of class B to another object of class A. But in your example 2, you are giving object B as an parameter.So you can create many objects of class A and give them the same object B

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112