Search code examples
c#.netclassinstances

How many instances of type will be created


I have two projects say BusinessLogic (BL) and DataAccess (DL). Now I am passing type as parameter from controller to BL and to DL in the end. Below is the code.

Controller

public ActionResult SomeAction (SomeClassForTable table)
{
    bool result = new ServiceInBL.DoSomeStuffWithParameter(table);
}

BL

public class ServiceInBL
{
    bool DoSomeStuffWithParameter (SomeClassForTable classForTable)
    {
        MethodForCrudInDL dl = new MethodForCrudInDL();
        return dl.DoSomeStuffWithParameter(classForTable);
    }
}

DL

public class MethodForCrudInDL
{
    public bool DoSomeStuffWithParameter (SomeClassForTable classForTable)
    {
        return true;
    }
}

SomeClass

public class SomeClassForTable
{
    // type members
}

From my controller, I am calling method in BL and from BL, calling method in DL. Now I want to know that how many instances of SomeClassForTable will be created in memory through out the process? Will there be three instances (BL, DL, and the one in controller)?


Solution

  • You haven't shown any instances being created - but passing a reference from one method to doesn't implicitly create a new instance, no. It copies the reference, not the object. It doesn't matter whether the methods are in the same assembly or not.

    Objects can be created implicitly in this sort of situation, if there's a user-defined implicit conversion involved. For example:

    public void Method1(string x)
    {
        Method2(x);
    }
    
    public void Method2(XNamespace ns)
    {
    }
    

    Here the call to Method2 uses a user-defined implicit conversion from string to XNamespace, which can create a new object. But if there's a reference conversion between the parameter type and the argument type (e.g. if they're the same type, or the method parameter type is a base class of the argument type) then the reference will simply be copied as the initial value of the parameter.

    Things get more complicated if different AppDomains are involved, but I suspect you're not in that situation (fortunately).