Most of the book never talk about how a program execute and how memory is allocated for them on stack and heap. when data stored on stack and when on heap.
Suppose i have one regular class like
public class MyClass
{
int Age=0;
string strName="None"
Double Salary=0;
public void Data1()
{
Age=30;
strName="Robin";
Salary=3500;
}
}
Question
1) so for the above class how memory will be allocated. when program run the memory will be allocated or when we create instance then memory will be allocated. when we call Data1() through instance then what happen and how memory will be allocated. memory will be allocated for function call or for data member initialization? tell me how much memory will be allocated for age, name and salary. memory will be allocated on stack or heap.
public class MyClass
{
static int y=0;
static string strComp="None"
int Age=0;
string strName="None"
Double Salary=0;
public void Data1()
{
Age=30;
strName="Robin";
Salary=3500;
}
public static void Data3()
{
y=50;
strComp="Hello";
}
}
2) how and when memory is allocated for static data member and function. when we call like
MyClass.Data3() then memory will be allocated or when we just run the apps. memory is allocated on heap or stack?
3) how memroy is allocated for static class. static class stored on heap or stack…if stack then why?
here i asked asked couple of question please explain in detail. thanks.
1.) Memory will be allocated when you create an instance of the class. When you call
Data1()no additional memory is needed as you are only referencing fields of the class instance (and no other local variables). SinceMyClassis a reference type, memory will be allocated on the managed heap.2.) Static methods do not consume any memory. Static fields are initialized before you access any static field or create any instance of the type they are contained in (
MyClassin this case)3.) You cannot create an instance of a static class so no memory is allocated dynamically, only when the type itself is created. Static classes are guaranteed to be loaded and to have their fields initialized and their static constructor called before the class is referenced for the first time in your program. Once created a static class remains in memory until your application domain is shut down.