C# Interview Questions :- Stack Heap in C#| Boxing Unboxing in C# | Value Type Reference Type in C#

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what happens due to boxing and unboxing unboxing unboxing decreases performance you know why because you have to jump between the memory types in this case you don't have any option but you have to say convert dot to end good morning good afternoon good evening namaste salaamwalekum satsriyakaal wanna come uh from whichever location you are watching this video so what are we doing today today we are covering c sharp interview questions and answers with code demonstrations around six important topics stack heap value type reference type boxing and unboxing so basically what i have done here is you know we have around 21 questions we have around 21 questions i'm flashing on the screen all the 21 questions and it's going to be a one hour of super duper awesome video one thing which i can guarantee out here is that once you see this one hour of video right you go to any c sharp interview and if you are asked questions around any one of these six important concepts it's a hundred percent guarantee from me that you should be able to tackle the questions right so 21 questions we are trying to cover one hour of video and uh you know the speciality of this uh six important topics are there very much interconnected i'm into like i'm going to say like for example if the interviewer is asking you question around stack and heap a very natural question or a connected question will go on boxing unboxing if he's asking about boxing and unboxing then he will ask you about value types and reference type so all of this you know six things are very much interconnected so when one is asked there is a high probability that the other question will be asked right so with all that thought process you know let us get started with the first question explain stack and heap what exactly is a stack what exactly is a heap when any application runs for example you can see we have the c sharp application out here which is running and you can see that the c-sharp application while it is running you know it needs it it is actually having certain variables and objects and you can see that there is a variable here an int variable of there is a boolean variable there is an object right so you know these variables you know they have to be stored into memory right so at least when the application is running this this variables have to be stored in certain kind of a memory so stack and heaps are nothing but their memories where application variables object pointers object references are stored right clean now one more question which comes and i understand that it's a very very newer question i will say but must be here the interviewer is just trying to trick you right so where exactly is this stack and heap stored are they stored into hard disk so where exactly it is stored right both stack and heap are stored in ram random access memory and not on a hard disk right the next obvious question is what kind of data goes on stack or what kind of variables goes on stack and what kind of variables go on a heap now many developers what they do here is you know they answer very bluntly saying that primitive data types are stored on stack and objects are stored on heap now this answer is definitely partially correct and in interviews when you answer a partially correct answer you will but obviously you will get cross questions and those cross questions can lead to more cross questions right so let us try to answer this question more accurately on stack primitive data types are stored or we can say value types are stored right so primitive data types means int boolean these are primitive data types so those are stored on stack plus object reference pointers are stored right object reference are stored so means in other words you can see that this is a test this obj is a test object right now this obj object pointer is stored on stack but the name and age this obj data is stored on heap right so on heap actual objects or reference types are stored now this is a very important thing depending on implementation even primitive data types can be stored let me answer this question again on stack primitive data types are stored plus object reference pointers are stored right while on heap actual objects or reference types are stored and depending on implementation even primitive data types are stored this last thing is also thing is very important that even primitive data types can go on heap and we'll come to that situation we will talk about that situation uh you know after some time so now let's try to see a demo you know so that the answer you know what we have just said it gets more solidified remember when you do a demo or you do a practical it gives you a different level of confidence in the interview while you are cross questioned you know by the interviewer so you can see over here i have a very simple console application and this console application i have defined three variables integer y int an object which is of the type class right class test you can see that i have this class test out here which has name and age so i have created this object of class test and we have the a boolean variable as well with the name xbool and what i've done is you know i have divided this code into two parts in the first part i have just declared the variables i mean like i've just said into y end and test object and then later on from line number 13 i've started putting the values so you can see here in line number 13 we have we are saying why int is equal to 100 and then in line number 14 15 and 16 i have initialized the object and later on i've initialized the x boolean equal to true so the so basically now when this application is running right the first three variables the three variables out here till line number 12 are not having any values right so uh let us try to understand you know that how these values are allocated on a stack and a heap right so i'm going to go and right click and add this variable to an add watch window so you can see here when we add a variable uh to an ad watch window we see a value you can see at this moment i did not initialize with the value and it is an integer data type so he has made the value as zero okay but we are not interested really in the value we are interested in the memory addresses remember at this moment we want to understand stack and heap so we are more interested in the in the in the variable memory addresses right so uh so now to see the variable memory address we have to go and say and why int so if you just say why int you see the see the actual value but when you say and y and right you see the memory address right so what we'll do is let us go ahead first and let us put all the three variables uh memory addresses out here so what i'll do is let me start from bottom here i'll say and x bool so let us put each one of these variables out here this is an object so and object right and then finally we have and y int so you can see here what i've done is i have actually uh you know we now know the memory addresses of these uh variables out here right so you can see here the x bool is positioned somewhere in e404 the object is somewhere in e408 and the y into somewhere in e414 right so this is an hexadecimal value which is actually saying that this x bool is located now in this hexadecimal memory address space on the ram this 7e408 hexadecimal value is saying that the object reference is stored into this location right so we are actually getting the location now let us try to understand this first you know if we understand this you know then stack and heap would be very clear right so what i'm going to do is i'm going to go and take a print shot of this and let me try to explain you what is happening out here now the first thing which i want your eyes to catch here is that the memory addresses of the variables means of all these variables you know which are there in the method are contiguous in nature right means they are just one after another there is no gap in between the memory addresses so look at this this is x bool here right so for x bull you can see zero x zero zero zero zero three four eight five b seven e four four look at the obj's address out here 0x003485b7e408 for now leave this 0x000 for that for now leave that address we'll come to that later on look at y into 0x003485b7e414 so we can see 404 408 414 so they are contiguous in nature they are there is no gap in between means you know it's not like you know that x bull is lying somewhere here and then obj is lying somewhere here no they are one after another and that's why it is a stack stack memory for now leave the heap aside you know leave the heap aside okay so you can see here we can say that okay down you know we have e414 and here we have y int after that you know we have obj right which is located at e408 at this point i'm not writing this big address here 0 0 3 4 8 5 b 7 you know because that is all common right and then we have x bool which is e 4 4 right so you can see that the way the variables are allocated it is it is a stack this is a stack this is a stack memory it is one above another it is contiguous in nature it is just side by side there is no gap in between them right that's how the stack memory is and stack follows lifo last in first out means what for example you can see here this is x bool which is the last variable it is now in the stack and when the application finishes you know at this point you know the application will exit and when the application exits right it will first remove this then it will remove this and then the first one which was inserted will be removed last so it follows lifo again this is a very important thing in interviews he can ask him that how is the memory deallocated right so it is lethal okay so i'm trying to summarize you know that what what we are trying to say here two points i want to say first thing the memory addresses are contiguous second it is a stack memory and it goes with the lifo style last in first out so when the memory is cleared you know when when when the application stops executing and it exits right the way the the memory is cleared it is from the top right remember it's a stack right so for example if you have a stack of a book right or if you have stack of clothes so you know what you will do you know you will you will first whichever is the last will be coming out first and whichever is the first will come out last right so it follows the lifo style so remember that in the interview in case you know the interviewer asks you that how does stack work it is lefo so while releasing the memory out to the operating system it will follow the leaf style now before we go to the next question right uh i want to make an announcement to everyone out here if you go and if you share this video on linkedin on facebook on twitter or somewhere out there right i will give you this ebook this ebook covers you know some very very important sharp interview questions with answers with code demonstrations so basically it will help you to clear uh at least the basic part of the interview right uh so if you go and if you share what you can do is once you share right just send us a mail at quespondequestpoint.com and we are more than happy to give you this ebook now also i would like to highlight here that down below in the comments if you go to the comments down below right you will see that you know i have highlighted a comment and in that comment you know we have we have like one hour of free video on c-sharp interview questions on sql server interview questions on angular interview questions on mvc interview questions and many more interview questions out there i would suggest that you can take a benefit of that if you go and if you subscribe to our quest pawns teachable if you subscribe to quespond.com you would get all of these courses you know as part of the subscription right so let us start with the next question one more important thing we should derive from this snapshot is how the values are stored if you see here for example now uh if you see y int you know this is an integer data type it is it is a primitive data type right primitive means basic data types like integer boolean uh double and so on right so those are primitive data types okay so you can see here this y int is out here this is the memory address and you can see down below i've expanded this right and the value is stored right out here so wherever the memory address is the value is stored right away out here now let's look at the another primitive data type we have boolean so you can see xbool is here this is the memory address 404 right and the value is stored right out here at this moment it is not initialized so the value is false integer if you are not initialized the value is zero right but the value is stored wherever the memory addresses so the memory address points directly to the value right in case of primitive data type now let's look at this obj if you see this obj this obj is located at e408 at this moment you know this obj is not instantiated remember our debug point is right out here we have still not executed this part of the code right this is still not executed so the obj at this moment you can think about it is not pointing towards anything right so you will see here this obj at this moment is not pointing towards the actual data it is pointing towards a memory address right it is pointing towards a memory address so one more thing which we need to derive from this is that in a stack this is a stack right in a stack the primitive data types the primitive data types memory address points towards the value but when you talk about objects when you create an object so in case of an object it points towards another memory pointer right and that memory address will point towards the value so you can see at this moment there is nothing so that's why it is showing zero zero zero zero zero because there is no value at this moment the object is null or it is nothing i will say so here you know he is once you know this code is executed this will point towards that memory address and the value will be stored in that memory address right and that is nothing but the heap so this is a stack and this is a heap in stack what goes in stack primitive data types go the values also go here primitive data types go the values also go here but when it comes to objects a pointer is stored on the stack there is a pointer which is stored on the stack and the actual data is then stored on the heap right so let us go ahead and execute this program and let us try to see that you know how things changes so there you can see we are debugging right so at this moment uh nothing is initialized uh remember that when the application runs right the compiler already knows you know the variables and so on right so you can see the variables are already allocated their memory addresses are already allocated only thing is that you know the values will go on later on right so now let us go here you can see this is false this is zero at this moment the obj is also not pointing towards anything so let us go one step on one step by one step so when i say y int equal to 100 you can see the value is now your 100 right if you go and if you move ahead you can see now look at this this value is true you can see now the obj is now pointing towards an actual address previously it was zero zero zero why you know because um there was no object but you can see now it is at at this moment it is pointing towards another object right let us take a pressure out from this you know and let us try to understand a few things uh on this print shot right so let me go here and let us try to understand some more points on the screenshot because at this moment the values are instantiated the values are assigned the object is assigned right so certain things have changed in the snapshot let us try to understand it now let us focus on this image because this image has the data now i'm going to again repeat everything about the stack right and also i will introduce you know how the heap is working okay so i know that i'm i'm reiterating i'm revising but see at the end of the day you know we want to clear the interview right and especially around this stack and heap and boxing and boxing and garbage collection right there are many small small things here and there you know and if you answer something wrong or if you answer something which is partially correct right it will just lead to more questions right so let us spend some time and one thing i can guarantee right this is super saturated guarantee that if you go through this video properly 100 nobody will catch your hand on stack and heap during the interviews right so let us iterate again so here it is this is a stack right and remember that we have three variables uh and stack goes lifo last in first out so there it is the first uh the first thing is uh y int right so y int will go on the bottom out here and because this is a primitive data type so remember why int at this moment is stored in e814 so we'll just write it out there e814 and uh the value is hundred so in case of limited type the memory address directly points towards the value right so that is the value after that we have the object right now remember that at this moment the object has data name issue and value 100 and where it is located e808 remember this is contiguous right so this is where the object is now you can see here this object is not pointing towards the actual data it is pointing towards an another memory address previously it was zero zero zero zero zero why because our object was not instantiated but now it is normal zero zero zero it is zero zero zero zero one b six eight zero zero zero a d 0 right which means that it is now pointing towards an address and this address you know is located somewhere right and that somewhere is nothing but the heap remember this is a stack this is a heap right so on the heap you know this value shift and 100 is stored right and after that we have our x bool again it is a primitive data type the value is stored wherever the address is so this is true and it is located at e804 right so you can see that is the stack right that is the heap now one very important point out here if you look at the [Applause] the memory addresses of stack you can see here e808 e814 e804 these are all contiguous look at the memory address of the heap somewhere it is you know if you look at this memory address zero zero nine five e c e c three seven e c ec37e80 ec but look at this memory it is somewhere different you know 68 000 adc 0. so it is located somewhere on the heap right it is not a part of the stack so that this memory address value here it it clearly says that it is not a part of the stack right so what goes on the stack now again reiterating that answer on stack primitive data types go right the values of the primitive types go on the stack and also objects and the reference pointer object reference pointers not the actual object data those go on the stack right and on the heap the actual object data the actual object data and also primitive data types can go if you look at this age here you can see this age is equal to 100 this age is not stored on the stack it is stored out here so in case if the primitive data type is a part of an object then it will go on a heap right so that is the complete answer you know what goes on a stack i repeat this again on the stack primitive data types plus object reference pointers will go what will go on a heap actual object data and also primitive data types in case it is a part of an instance so one favorite question of the interviewer always comes is that can primitive data types like integer and boolean can go on a heap the answer is yes if it is a part of an object instance like this it can go on a hip it will go on a heap not can it will go on a heap if the same primitive data type is is standalone like this you can see here this into y end if it is if it is standalone like this i'm sorry my pen is blinking out here what happened hang on okay so if if you see this into y into like this this will actually go on a stack and not on a heap right so i think this answer when you're answering right and main it's a it's a favorite of many interviewers can primitive data types go on a heap yes depending on how it is implemented part of the object it will go on the heap if it is not part of the object if it is it's inside this method or a function standalone it will go on a stack so what goes on stack what goes on heap let us try to conclude a very good answer out here so on stack primitive values are stored plus object reference pointers that means the object data is actually not stored on stack you know the reference pointer is stored and second on heap actual object data is stored plus primitive data types can also get stored depending on situation like you know where the primitive data type is a part of an object so that's the answer you know the interviewer is expecting so try to give a holistic end to end a fully what you call truthful answer you know so that you don't get into cross questions now when you talk about stack and heap right you will definitely get you know some questions on what are value types what are reference types or you can say what is bival and what is biref what is uh you know copy by val and what is copy by ref you know so all these words are all synonyms you know so in other words what are value types and what are reference types right so let us try to understand them one of the questions you know which has come to my mind is as i was going through these questions and answers and demonstration that if a developer is not able to answer these questions does not that make him a good developer should not be selective because i know that i know many developers out there who very well execute projects they don't understand stack and heap they don't understand these boxing unboxing but they fantastically you know they actually go and execute a project they make it live customers are happy now in this you know there are two schools of thought one school of thought says that we should ask questions on around only what they are working on for example if he says i worked on sql ask on sql if he says uh i have worked on this you know ask questions only around you know things what he has worked on but then there is another school of thought also who says that no like see at the end of the day if he does not understand stack and heap if he does not understand the performance issues of boxing unboxing how can he create good applications right so there are two schools of thought out here i want to know from everyone out here what do you think do you think that these questions you know they should be able to answer these are fundamental questions or you say no like it's okay if they are not able to answer right so let me know from which school of thought you are on the comments below it will help me to also get more matured but at the end of the day interviewer is the king and these questions are asked in the interview you like it or you don't like it right so we are here to clear the interview so let us move to the next question so let us first start with value types and reference type value types are primitive data types reference types are objects i'll repeat this value types are primitive data types while reference types are objects now you will say then you know why are we saying reference type why are we saying value types and if we can just say primitive we can just say objects right it is because of the behavior you know these variable exhibits you know when you assign a value so when you actually assign a value for example you can see in this line out here we are trying to assign uh a primitive data type value to another primitive type right and look at this over here where we are trying to assign an a reference to another reference type so when you know this assigning assignation happens right at that time you know there is a certain behavior which is exhibited and because of that behavior it is termed as value types and reference type so let us try to understand that behavior in order to make you understand the behavior what i have done out here is you can see here you know i have this code out here and this code is completely executed and i've created a snapshot you know with all the variable addresses out here so in this code what we have is we have two variables out here at the top one is y int which i have assigned uh with the value hundred so this is a primitive data type and then i have created an object uh which is of the type test which has name and age and then later on in the later part of the code what i'm doing is i'm assigning this y into z int and i'm assigning this obj over here to obj-1 right so let us try to understand that what happens out here so first thing uh you know you can see that this is a stack out here and you can see all the memory addresses out here so first thing e794 e794 is where we have our y int which is hundred then we have the obj which is e788 and this obj as we said you know it it has a pointer here adc 0 and the value shift and 100 is allocated on the heap right now what we are doing in this line out here we are trying to assign y into z end now look at this when we do that right the z int is having a new memory address e784 so this is z int and in that z end you know we have the value 100 right now let us look at this statement out here what happens when you allocate obj to obj one so the obj one is is there again here on this e778 is obj1 and you will see here that this obj one is pointing towards the same adc 0. you can see both the addresses of obj and obj one are equal so this is also pointing towards adc 0 means what that this is actually pointing towards the same data out here so yes you know the object pointers have different memory address but you know the the inside pointer you know is pointing towards the same data so what is the big difference out here when we actually assign the value types when we assign the value types a fresh copy of the of the variable was created a fresh memory address was created so this e794 value was copied to e784 which is a different address and it was allocated completely different decoupled so if i if i go and change this to 200 this is not going to go and change e794 so that's why it is termed as value types a lot of people also say this is copy by value why because you are copying by value it has fresh memory address it has no connection with the previous address now look at you know this when obj was allocated to obj-1 in this case you know if you see yes there is a new memory address for the pointer for the pointer but both the pointers it is just copying the references he just copied the memory address out here this adc 0 was copied to copied over here not the actual data he did not make a copy out here huh guys this did not happen so this is called as copy by ref right copy by value copy by reference so the interviewer can ask you questions in different ways he can say okay what are value types and reference types so value types are nothing but primitive types you know vary in the value though the values are copied and a fresh memory address is created while in case of references when you actually move the objects reference are copied they point towards the same data if you go and if you change this shift to shiva it will change for obj also it will change for obj one also for both of them this this data will change because both of them are pointing towards the same memory address so the interviewer can ask you in various ways out here you can say explain you know copy by val versus copy by ref or you can say value type versus reference types uh or you can say you know what do you mean by by val and by ref if you get any one of these questions you know he is expecting the answer that one is copied by value and another one is copied by the memory address that is the reference so if you are asked a question on stack and heaps if you are asked a question on value types and reference types very but obvious or i will say there is a high probability that you will be asked a question on boxing and unboxing right so what is boxing and unboxing boxing and unboxing is nothing but uh it is a process you know which happens you know when your variable jumps from a stack to a heap and from a heap to a stack so when the variable jumps from a stack to a heap it is termed as boxing and when the variable jumps from a heap to a stack it is called as unboxing remember in an interview when you're asked a question that what is boxing uh and if you don't remember like is it from a stack to a heap or from a heap to a stack right you can just remember like this saying that okay i will box things up and throw it in a heap and i repeat this you will box something up like you will block box your clothes you will box your books and you will just throw it you know in a heap right so boxing is nothing but you know moving from when your variables actually move from a stack to a heap right and unboxing is when your uh variables moves from heap to a stack okay so so let us try to understand uh you know what happens in boxing and unboxing uh you know why are the code and why are the memory addresses so you can see that we have a very simple code here it is just a three line code so in this first line you know we are assigning int i equal to 100 now remember that this is a value type and in the second line we are trying to move this value type to a reference type right so this is where boxing will happen right and then you can see in the third line out here i'm trying to move this object to integer so i'm using this convert function so this is where unboxing happens right and let us see what happens out here right so let's draw our memory addresses we have a stack we have a heap right so first thing uh we will see here int i 100 e794 so where we have int i equal to 100 right okay after that this int i is moved to an object right now what happens out here you can see the reference pointers object out here is e788 it is out here so this is obj and he's pointing towards this another memory address remember this is by ref so it points towards ada0 and that ada0 now has value 100. so what has happened out here is when you actually try to move this int i to object right it actually copied this value into the heap right so this is this is where we are seeing boxing has happened because it has copied the value and then assigned the variable now look at the third line so if you look at the third line in z in zed is e 784 right and in z it is now 100 right now in this case what happened you know this object value is data is now converted into integer and a copy is made this is unboxing right so you can see that uh very clearly you know when you're moving this data type values actually from a heap to a stack and a stack to a heap an actual copy happens it actually copies it actually creates a new memory it actually allocates value and so on so it's quite a a resource intensive process so one of the next question in a visa interviewer can ask you is that so is boxing and unboxing good no definitely as a developer we should try to avoid boxing and unboxing as far as possible you know if you if you remember our first video you know our first she sharp interview question video where i had shown a simple demo that how boxing and unboxing uh you know can lead to a lot of uh what you call you know boxing unboxing can lead to a lot of uh issues with the performance right and we'll see a demo also let me see that if i can get a chance to show you the demo as well right so definitely moving values you know from a from one memory type to another memory type remember this is a completely different memory type heap and this is a completely different memory type stack so when you're moving a value between heap and a stack and a stack and a heap definitely your performance will decrease right so you should try to avoid it as far as possible but the reality is that it is unavoidable there are many situations you know wherein it is unavoidable so one of the things which the interviewer wants to hear is that we should avoid it for example in this case out here this is really really a bad practice i mean there is no point of moving this integer into object there is no point of moving object to integer right so such kind of thing should be avoided but then you know there are some situations like this you know for example look at this let us say that you are taking an input so now let us say you are taking an input out here let us say you are taking a age input right so you write your console.readline now if you see out here this console.readline out here it is a string you can see this is a string and remember strings are objects we'll come to that later on after this the next question is that our string primitive data types are objects we'll talk about it now this is a string it's an object and what you do is you are taking the input from the keyboard right so in this case you don't have any option but you have to say convert dot to int right so when you're taking the input from a text box from a combo box from a ui into a variable or must be you are trying to bind your variable to a grade right in such cases you know boxing and unboxing is unavoidable right but unnecessarily you know you know doing like this you know does not make sense let me show a small code out here that how boxy and unboxing you know actually affects performance right so what i will do is let me go here and write a simple code so let me write a static void check performance okay let's write a simple thing out here and what we'll do is first we will so this check performance what we'll do is we will run it uh let us do like this now let us run this code this block of code for thousand times let us let us try to check performance okay so we'll just run it like 1000 times or must be much more than that i'm running it right so we are trying to run this code in a big loop out here right and what we'll do is that we will use the stopwatch right so we'll use the stopwatch to check the performance stopwatch is a nice class given out here in c sharp you know which helps you to uh it's it's a class which is in system dot diagnostics it helps you to accurately measure time uh it actually when you're talking about performance if you want to measure something then this is the watch because it gives you an accurate time if you're using the date and time clock you know then there are little bit of inaccuracies out there but here this is like quite accurate right so i use it you know sometimes you have to measure performance so i'll just say new stopwatch out here right and uh i will say start the stopwatch right and uh we will run this check performance and we will stop the stopwatch right great so um and what we will do is remember that in dot net what happens is the il code gets converted into uh machine code so first thing when you compile it is an il code and then later on the il code gets converted into a machine code so what i'll do is i'll just run this check performance multiple times first you know just to make sure that our il code is converted into machine code and we are not measuring the time of conversion of il code to machine code right and i will just do a console.readout here and i will also do a console.writeline uh saying that you know tell me what is the elapsed sticks of the stopwatch right so uh at this moment you know what what i'm doing is i'm trying to move we are actually doing boxing unboxing so basically we are actually moving up we are actually doing boxing so we are actually moving unnecessarily of a primitive type to an object right so let us see what happens here so i'm going to go and run this right so that it is running and let us see uh it will take a little bit of time see remember whenever you read something you know when someone says that okay boxing and unboxing decreases performance you should write you know such kind of small code and solidify your thought process or solidify your knowledge or as what happens you know like you just read it but you know until you don't see it until you don't do some demo right it does not get registered into your head uh it is taking a bit time you know must be because oh it's it had already ran at the back so there it is four six zero nine i'll just run it multiple times just to make sure it's the same thing four six three three four six zero nine four six three three seven six four five suddenly it is seven six four five uh five six two five you know whenever you are measuring performance right you know just make sure that it is consistent it is not like sometimes it is four and sometimes it is forty thousand right so i'm just running this multiple times you know to just check so 7045 and then 6355 you know and uh 4800 so 4000 to 7000 is the range you know i'll just put it down out here in the notepad that with boxing and unboxing our range you know was uh 4 000 to 7000 right that was the range now what we'll do is we'll go and we'll remove uh boxing unboxing so i will just make this as in z okay so there is no boxing unboxing now we are just moving from a value type to a value type right now let us measure the performance let us see you can see now 1996 look at it it's almost four times lower even if i take the middle range out there you saw that as soon as you know that boxing unboxing was involved right suddenly because you have to allocate it on a stack you have to find something on a stack that's why you know we had this huge range out here of 4000 to 7000 but look at this look at when you're moving within the stack right it is almost consistent in that 1000 range you know so it's the difference is hardly 100 or 200 you know as you can see almost it is 1500 almost every time when i run it is almost 1500 and it never 15 so you can say 1 000 to 2 000 right if i if i try to conclude this it is almost 1 000 to 2 000 almost okay so if you look at this difference so look at this this is the difference you know when you had boxing and this is a difference you know when you when you do not have boxing so you can see that how the performance is impacted so remember you know whenever the interviewer asks you that what happens due to boxing and unboxing unboxing unboxing decreases performance you know why because you have to jump between the memory types second is boxing and unboxing avoidable there are certain situations you know where you take data from the ui or must be your primitive data types you are binding to the grid it is it is completely unavoidable because you have to you have to do it isn't it but unnecessarily doing boxing and unboxing you know those kind of code you know should be removed right so so so remember this that boxing and unboxing decreases performance right and it should be avoided as a best practice one more question it's a tricky question you know which the interviewer can ask you is that are string objects or value types our strings are located on a stack or r strings are located on a heap right so if you see here this is string x and i'm i'm putting a value shift and if you see the memory address uh structure of x you will see that it is a reference type look at this this is x here which is the the 760 760 is the memory address of the pointer and the actual value shape is stored into heap in this address 6 to 8. so you can see this is actually a reference type so strings are objects they are reference types they are allocated on a heap please understand and whenever you try to move like this you know a value type you know to a string remember it is doing boxing and unboxing so if you're trying to move a premature data type to a string or vice versa that means that you are actually doing boxing and unboxing so uh you know from this image it is very clear that strings are objects strings are reference types strings are allocated on a heap there is one more tricky question you know which comes around stacks and heaps you know while she shop interviews is that how many stacks are created and how many heaps are created so let us try to understand this one stack is created per thread i repeat this sentence one stack is created per thread and there is only one heap created at least to my best knowledge there is only one heap created yes you know there are extraordinary situations where you know multiple heaps can be created but it is a very extraordinary situation and i don't want to discuss that situation now but one heap is allocated to an application and stack is created per thread so you can see here now for example this is static void main so the application this static void main will run in one thread so int i and y will be put on a stack put on stack one you can say and you can see i'm creating one more thread here and i'm running function one in that thread right in case you are new to threading you know please see our threading videos uh which are there so you can see here i've created a thread and i'm running function one in this thread now for x and y one a separate stack will be created so if i run this so you can see here and in i right and let us say and y okay this is one now uh let us try to go inside the thread right so let us try to go inside the thread out there so t dot start right and let us try to also get the memory addresses of uh and x and let us try to get the memory addresses of and y1 if you see here uh i'll i'll just take a print shot and let us let us try to see you know what is happening right so i'm going to go and take a print shot and just let us zoom here and let us try to see what is happening you can see here very clearly for this static void main one thread is created so for that there is a stack created and you can see here the y right the int i and y are allocated on one stack and how do you know it is on one stack look at this numbers out here they are contiguous you know so e718 sorry it is a p718 and e724 right contiguous now look at the down numbers which is because for here i have created a new thread right so this is running on a different thread these numbers are not contiguous like the top so that is a different stack actually so over here now you can see the numbers are you know for y 1 it is 4 e 8 right and then you have 4 f 4 right so this is a different stack and this is a different stack so this is the stack which is allocated to the main thread right and this is the stack you know which is allocated to this thread t which we have created right and definitely you know there is only one heap created so if there are any object reference pointers we do have this y etc which is there referencing the objects but they are then created on the heap so there is one heap and per thread one stack is created one of the things you know which an interviewer would like to test [Music] is that do you know how the memory de-allocation takes place see when any application runs and once the application exits one of the most important thing is that whatever memory it is consuming it has to give it back to the operating system if it is not giving back that memory to the operating system it leads to memory leak and memory leak is not a good idea just think about it you have an application which is running you have exited it and still it is holding some memory right so that would be a bad situation so whatever memory is allocated either it is on a stack or either it is on a heap it should be given back gracefully to the operating system so one of the questions you know which the interviewer can ask you is that how is the stack and the heap memory de-allocated or how is this memory given back to the operating system so let us try to understand it so here is a simple code out here so let us let us try to understand by using this code that how the memory is allocated and deallocated so let me first draw the diagram for stack and heap i do understand that i'm drawing this diagram many times i'm reiterating reiterating it many times but believe me that you know when you reiterate something many times it just gets registered in your head right so we have int i so down below in the stack somewhere int i will be created uh with the value 10 and then we have in z right so in z is created here with the value 100 and then we have the y object and because it is an object here there will be a reference pointer and that reference pointer will point something on the heap and on the heap we will have shiv and 10 right which is there right so the scope of this whole thing is from here to here so whenever this thread exits you know so when this thread exits from this point right we want that all the memory you know whatever is allocated here on the stack and on the heap should be given back to the operating system that is the most important thing which should happen right so uh after this point what happens now after this point first thing it is very easy to de-allocate a stack you know because the stack as we said is contiguous in nature right so what happens is as soon as this point gets uh executed right after this or it goes out of scope these variables go out of scope right this complete thing out here gets this whatever is a memory out here is poured like a bucket you know it's a stack you know it's poured like a bucket and it is given back to the operating system so we don't have to worry about this this happens immediately this happens immediately you know after this point is executed but then what about the heap the heap memory is still out there right now the heap memory i remember is not contiguous you know you can have some memory here you can have some memory here you can have some memory here right and uh so how does this deal who goes and deallocates this because here it is very tough you know that sometimes you know something is empty sometimes you know something it is not contiguous in other words the memory allocation is not contagious out here right see whenever something is continuous right it is very easy to dialog okay very easy to carry a stack you know think about a stack of a book it is very easy to carry from one place to another place a stack of clothes is very easy to carry from one place to another place you know it's because it is just one thing right but here in a heap you know something is getting allocated here something is getting de-allocated here it's difficult to know what to do right so the first thing is who de-allocates this so we have our friend out here called as the garbage collector the garbage collector comes undetermistically and deterministically means we don't know when it will come right but it comes undetermistically and it says that okay which which memory do not have references remember uh you know once uh once you know this this thing this whole thing goes off right from here the stack is deallocated from here right there is no reference of these values now there is there is no one referring here on the stack so the garbage collector comes and says okay who are those which are those memory addresses or which are those memory places you know which do not have any reference on the stack so this does not have it on a stack so the garbage collector comes and then gives back this to the operating system right so garbage collector goes and collect and garbage collector is the person who actually or the garbage collector is the process i'm sorry i'm saying it's a person just a habit so garbage collector is a process which runs in a background it comes and deterministically and goes and cleans any kind of objects on the heap right while stack de-allocation happens by itself so remember that in interview if you know one of the things you know is the interviewer is expecting from you is that you should know how the dr location take place so stacked memory are easy to deal locate easy to allocate while heat memories are it is easy to allocate but it is tough to deal lock it and the heap memory gets cleared by the garbage collector heap memory clear gets cleared by the garbage collector stack memory gets cleared automatically because we know you know how the memory address scheme is it is contiguous and so on right so this is what you have to communicate in the interview now there are three more questions you know which can come in when you talk about stack heap value type reference type and all these three questions are mostly revolving around structures question number one when you create a instance of a structure right or when you actually initialize a structure are they allocated on a stack or are they allocated on a heap second when you assign one structure to another structure does it exhibit a by well scenario or does it exhibit a by ref scenario so does it do you know does it copy the values right and creates a new in a new memory address or does it do a reference copy and the last one is is it possible that structures can also get allocated on a heap right so that's one more question right so you can see here i will not answer these three questions you know this image what you see out here already represents the answer right so you can see here what i've done is i've created a structure here called as my struct i have created an instance of the structure s1 so you can see out here this is s1 this is the memory address of s1 right and you can see the values so this actually answers the question number one i will not answer the question all the three answers i want you know the viewers our subscribers to please put down in the comments the answers of all the three questions already my screen is already answering it i will just uh you know show the code and explain you but if you can take all these three questions and answer them on the comment that means that you have understood my lessons right so here it is you can see this is s1 s1 this is the memory address and these are the values so that answers question number one are structures allocated on a stack or our structures are located on a heap now look at this you know we are assigning this s1 to s2 right so here it is this is s2 you can see s2's memory address out here and you can see the s1's memory address this answers the second question that whether structures exhibit a by val scenario or by ref scenario so are they do they do a copy by value or copy by reference right so by looking at this memory address by looking at these values you can easily understand that this line out here is it doing a copy by val or copy by ref the last question where i asked you that are there scenarios you know wherein the structures can get allocated on a heap so you can see here i have created a test class out here i have created a instance s3 and inside this i have created a structure so you can see there is s3 out here and you can see this thing right which answers our third question right so this answers question number one this answers question number two and this memory address out here answers question number three so i want that if you can go and put down in the comments by looking at the screen you can pause you can go ahead and you can hit the pause button and you can just watch this image and if you can conclude what the answer is and if you can write down down below that will really i will feel that yes you know people have understood you know what i have been speaking for the last one hour okay so we have covered like one hour of video now as a teacher as a trainer i want to know that how many people are watching me till here am i just alone speaking and nobody is watching me it's youtube right it's a c so in case if you are watching me till here if you are seeing this video if you are seeing this bottle out here right if you can just go and tell me on facebook.com correspond saying that yes we did watch you till one hour we liked your video or if there is any constructive feedback i'm more than happy to implement the same right why i'm saying this so they will help me to know that yes people are watching me till one hour i should record such kind of videos it will motivate me it will help me to you know create better videos so please do the needful okay okay so that brings us to the end of this video i hope you have liked it now what we'll do is we have covered 21 questions right let us go and do a quick revision right because till now you were seeing the practicals you were seeing the demos right but at the end of the day if you don't revise right you will forget it so this video is now going to end but a quick revision will be done and please note as we said if you go and if you share this video on facebook if you share this video on linkedin if you share this video on twitter right in any one of these social media channels you will get this ebook in which i am flashing right on the screen for free so happy learning happy job hunting let us start the revision you
Info
Channel: Questpond
Views: 9,630
Rating: undefined out of 5
Keywords: value type, reference type, heap, boxing and unboxing in C#, stack vs heap C#, value types vs reference types, difference between stack and heap, stack and heap memory, C# interview questions and answers, stack heap memory allocation, stack heap interview questions, what is stack memory, reference types, c# interview questions, boxing vs unboxing, boxing unboxing interview questions, value types reference types interview questions, boxing unboxing, stack heap, byval and byref
Id: 7O4JPdKjc30
Channel Id: undefined
Length: 62min 25sec (3745 seconds)
Published: Fri Sep 02 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.