简体   繁体   中英

Memory allocation under Methods in C# .Net

I'm still learning C# and I'm under difficult case understanding memory allocation in methods. Let's imagine the situation that I got some reference object, and in a method I'm assigning existing object, what will be done in memory?

I found Are instance methods duplicated in memory for each object? but it is not so clear for me in case that I describe. Any other references will be very much appreciated.

public class ClassToBeAssigned : IClassToBeAssigned {}
public interface IClassToBeAssigned{}

public class AllocatingClass
{
  private ClassToBeAssigned testAssigment;

  // Just as example
  void Main()
  {
       // new allocation in memory
       testAssigment = new ClassToBeAssigned();
       Assign(testAssigment);
  }

  // create here copy of context by assigned
  void Assign(IClassToBeAssigned assigned)
  {
       // What will happend now if there are 4x method calls ?
       DoSomething(assigned);
       DoSomething(assigned);
       DoSomething(assigned);
       DoSomething(assigned);
  }
  void DoSomething(IClassToBeAssigned assignIt)
  {
       // What is happening here in memory allocation for that reference each call ?
       IClassToBeAssigned dealWithIt = assignIt;
  }
}

I just got a bit confused about what is happening there, also I found lots of information, but nothing for this specific problem.

Assigning a reference doesn't create a copy in C#. You only create a new instance in Main , so there's only one instance of ClassToBeAssigned .

The exception is with value types; these need special care. If ClassToBeAssigned was a struct rather than a class , each call of Assign(testAssignment); would in fact create a new instance that is a copy of testAssignment . Note that even in this case, DoSomething(assignment); will not result in a new copy. If you want to understand more about this topic, read up on boxing in C#.

As for DoSomething , it does absolutely nothing, so it's not clear what you would expect to happen there :)

DoSomething would allocate some bytes from the stack for the dealWithIt variable, so depending on the system that would be 32 or 64 bits it allocates, since dealWithIt is just a reference.
The reference from assignIt would then be copied to that allocated memory, to then be immediately be released again, since the method is done and the stack moves back to the previous method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM