0
class Calculate
{
    int result;
    public int add(int m, int n)
    {
        result = m + n;
        return result;
    }
}
class Program
{
    static void Main(string[] args)
    {
        int a, b, c;
        a = 10;
        b = 20;
        Calculate obj;
        obj = new Calculate();
        c= obj.add(a, b);
        Console.WriteLine(c);
        Console.ReadLine();
    }
}

this is a sample code, I wonder how stack and heap functions, and who variables,methods,class or objects get stored, how stack is functioned line by line execution of code and if 10 objects are create how and where these are stored

virus
  • 13
  • 3
  • I found this [article](https://dev.to/tyrrrz/interview-question-heap-vs-stack-c-5aae) quite interesting. You need to understand the difference between reference type and value type. Then you can answer your question – WilliamW Jan 07 '20 at 12:27
  • 1
    Does this answer your question? [Memory allocation: Stack vs Heap?](https://stackoverflow.com/questions/4487289/memory-allocation-stack-vs-heap) – Diado Jan 07 '20 at 12:27

1 Answers1

0

Heap All reference types (strings, objects) and static variable types are stored on the heap.

Stack All value types are stored on the stack.

int result;

result will be on the heap too because it's a part of Calculate.

    int a, b, c;
    a = 10;
    b = 20;

a, b, c are all on the stack, because you give these variables a value on the main thread.

    Calculate obj;

obj will be on the heap, since it's a reference type.

For more information: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/data-types/value-types-and-reference-types

Jelle Schräder
  • 185
  • 2
  • 13
  • thanks for the info but what happens when only int a; is executed will memory gets allocated if it gets why compiler throws error when i write console.write(a); with out assigning – virus Jan 07 '20 at 12:39
  • Int a has no value. On the stack you define space for a variable named a, but the value is empty. Are you still using C# 4? Last year C# 8 came out. I know that value types have a default value and shouldn't throw errors that way. – Jelle Schräder Jan 07 '20 at 13:52
  • ohh! ok, thanks for that – virus Jan 07 '20 at 13:54