Stack and Heap Memory in C# with Examples - Dot Net Tutorials
文章推薦指數: 80 %
If the value type was declared as a method parameter then it's stored on the stack. If the value type was declared as a member of a class then it's stored on ... Skiptocontent Introduction&EnvironmentSetup HowComputerWorks IntroductiontoProgrammingLanguages HowComputerProgramsWorks DifferentTypesofApplications ProgrammingMethodologies Algorithm,Pseudocode,Programs,andFlowcharts Introductionto.NETFramework .NETFrameworkArchitectureandComponents IntroductiontoC#ProgrammingLanguage HowtoDownloadandInstallVisualStudioonWindows CreatingFirstConsoleApplicationusingVisualStudio C#.NETBasics BasicStructureofC#Program MethodsandPropertiesofConsoleClassinC# DataTypesinC# LiteralsinC# TypeCastinginC# VariablesinC# OperatorsinC# ControlFlowStatementsinC# If-ElseStatementsinC# SwitchStatementsinC# LoopsinC# WhileLoopinC# DoWhileLoopinC# ForLoopinC# BreakStatementinC# ContinueStatementinC# GotoStatementinC# FunctionsinC# User-DefinedFunctionsinC# CallbyValueandCallbyReferenceinC# RecursioninC# UserInputandOutputinC# CommandLineArgumentsinC# StringinC# StaticKeywordinC# StaticvsNon-StaticMembersinC# ConstandRead-OnlyinC# PropertiesinC# WhyweshouldoverridetheToStringmethodinC# OverrideEqualsMethodinC# DifferenceBetweenConvert.ToStringandToStringMethodinc# Checked and Unchecked KeywordsinC# StackandHeapMemoryinC# BoxingandUnboxinginC# OOPsinC# ObjectOrientedProgramming(OOPs)inC# ClassandObjectsinC# ConstructorsinC# TypesofConstructorsinC# WhyDoWeNeedConstructorsinC# StaticvsNon-StaticConstructorsinC# PrivateConstructorsinC# DestructorsinC# GarbageCollectioninC#.NET AccessSpecifiersinC# EncapsulationinC# AbstractioninC# InheritanceinC# TypesofInheritanceinC# HowtouseInheritanceinApplicationDevelopment IsAandHasARelationshipinC# GeneralizationandSpecializationinC# AbstractClassandAbstractMethodsinC# HowtoUseAbstractClassesandMethodsinC#Application InterfaceinC# MultipleInheritanceinC# PolymorphisminC# MethodOverloadinginC# OperatorOverloadinginC# MethodOverridinginC# MethodHidinginC# PartialClassesandPartialMethodsinC# SealedClassinC# ExtensionMethodsinC# StaticClassinC# VariableReferenceandInstanceofaClassinC# ExceptionHandling ExceptionHandlinginC# MultipleCatchBlocksandFinallyBlockinC# CustomExceptioninC# InnerExceptioninC# ExceptionHandlingAbuseinC# Delegates DelegatesinC# MulticastDelegatesinC# DelegatesReal-timeExampleinC# AnonymousMethodinC# LambdaExpressionsinC# GenericDelegatesinC# Multi-Threading MultithreadinginC# ConstructorsofThreadclassinC# HowtoPassDatatoThreadFunctioninTypeSafeMannerinC# HowtoRetrieveDatafromaThreadFunctioninC# IsAlivePropertyandJoinMethodofThreadClassinC# ThreadSynchronizationinC# LockinginC# MonitorClassinC# MutexClassinC# SemaphoreClassinC# SemaphoreSlimClassinC# DeadlockinC# PerformanceTestingofaMultithreadedApplication ThreadPoolinginC# ForegroundandBackgroundThreadsinC# AutoResetEventandManualResetEventinC# ThreadLifeCycleinC# ThreadsPrioritiesinC# HowtoTerminateaThreadinC# InterThreadCommunicationinC# HowtoDebugaMulti-threadedApplicationinC# CollectionsinC# ArraysinC# 2dArrayinC# AdvantagesandDisadvantagesofArraysinC# CollectionsinC# Non-GenericArrayListinC# Non-GenericHashtableinC# Non-GenericStackinC# Non-GenericQueueinC# Non-GenericSortedListinC# AdvantagesandDisadvantagesofNon-GenericCollectioninC# GenericCollectionsinC# GenericsinC# GenericConstraintsinC# GenericListCollectioninC# HowtoSortaListofComplexTypeinC# ComparisonDelegateinC# GenericDictionaryCollectionClassinC# ConversionBetweenArrayListandDictionaryinC# ListvsDictionaryinC# GenericStackCollectionClassinC# GenericQueueCollectionClassinC# ForeachLoopinC# GenericHashSetCollectionClassinC# GenericSortedListCollectionClassinC# GenericSortedSetCollectionClassinC# GenericSortedDictionaryCollectionClassinC# GenericLinkedListCollectionClassinC# ConcurrentCollectioninC# ConcurrentDictionaryCollectionClassinC# ConcurrentQueueCollectionClassinC# ConcurrentStackCollectionClassinC# ConcurrentBagCollectionClassinC# BlockingCollectionClassinC# FileHandling FileHandlinginC# FileStreamClassinC# StreamReaderandStreamWriterinC# FileClassinC# TextWriterandTextReaderinC# BinaryWriterandBinaryReaderinC# StringWriterandStringReaderinC# FileInfoClassinC# DirectoryInfoClassinC# AsynchronousProgramming IntroductiontoConcurrency AsyncandAwaitOperatorsinC# TaskinC# HowtoReturnaValuefromTaskinC# HowtoExecuteMultipleTasksinC# HowtoLimitNumberofConcurrentTasksinC# HowtoCancelaTaskinC#usingCancellationToken HowtoCreateSynchronousMethodusingTaskinC# RetryPatterninC# OnlyOnePatterninC# HowtoControltheResultofaTaskinC# Task-basedAsynchronousProgramminginC# ChainingTasksbyUsingContinuationTasks ValueTaskinC# HowtoCancelaNon-CancellableTaskinC# AsynchronousStreamsinC# HowtoCancelAsynchronousStreaminC# ParallelProgramming TaskParallelLibraryinC# ParallelForinC# ParallelForeachLoopinC# ParallelInvokeinC# MaximumDegreeofParallelisminC# HowtoCancelParallelOperationsinC# AtomicMethodsThreadSafetyandRaceConditionsinC# InterlockedvsLockinC# ParallelLINQinC# AutoMapper AutoMapperinC# AutoMapperComplexMappinginC# MappingComplextypetoPrimitiveTypeusingAutoMapperinC# AutoMapperReverseMapinC# AutoMapperConditionalMapping inC# AutoMapper IgnorePropertyinC# UseValueResolveUsingandNullSubstitutioninAutoMapper OptionalParameter,IndexersandEnums HowtomakeOptionalParametersinC# IndexersinC# IndexersReal-TimeExampleinC# EnumsinC# .NETFrameworkArchitecture DOTNETFramework CommonLanguageRuntimein.NET .NETProgramExecutionProcess IntermediateLanguage(ILDASM&ILASM)CodeinC# CommonTypeSystemin.NETFramework CommonLanguageSpecificationin.NETFramework ManagedandUnmanagedCodein.NET AssemblyDLLEXEin.NETFramework AppDomainin.NETFramework StrongandWeakAssembliesin.NET Var,DynamicandReflection ReflectioninC# DynamicTypeinC# VarKeywordinC# VarvsDynamicinC# DynamicvsReflectioninC# VolatileKeywordinC# RefvsOutinC# NamedParametersinC# C#7.XnewFeatures C#7NewFeatures OutVariablesinC# PatternMatchinginC# DigitSeparatorsinC# TuplesinC# SplittingTuplesinC# LocalFunctionsinC# RefReturnsandRefLocalsinC# GeneralizedAsyncReturnTypesinC# ExpressionBodiedMembersinC# ThrownExpression in C# AsyncMain in C# C#8NewFeatures C#8NewFeatures ReadOnlyStructsinC# DefaultInterfaceMethodsinC# PatternMatchinginC# UsingDeclarationsinC# StaticLocalFunctionsinC# DisposableRefStructsinC# NullableReferenceTypesinC# AsynchronousStreamsinC# AsynchronousDisposableinC# IndicesandRangesinC# Null-CoalescingAssignmentOperatorinC# UnmanagedConstructedTypesinC# StackallocinNestedExpressionsinC# OnlineTraining OurC#.NETOnlineTrainingProgram MostPopularC#Books MostRecommendedC#Books MostRecommendedDataStructureandAlgorithmsBooksusingC# Backto:C#.NETTutorialsForBeginnersandProfessionalsStackandHeapMemoryinC#withExamples Inthisarticle,IamgoingtodiscussStackandHeapMemoryinC#ApplicationwithExamples.Pleasereadourpreviousarticle,wherewediscussedtheCheckedandUncheckedKeywordsinC#withExamples.Aspartofthisarticle,first,wewilldiscusswhathappensinternallywhenwedeclareavariableofvaluetypesaswellasreferencetypes.Thenwewillmoveforwardandlearntwoimportantconceptsi.e.stackandheapmemoryaswellaswewilltalkaboutvaluetypesandreferencetypes. Whathappensinternallywhenwedeclareavariablein.NETApplication? Whenwedeclareavariableina.NETapplication,itallocatessomememoryintheRAM.ThememorythatitallocatesinRAMhasthreethingsareasfollows: Nameofthevariable, Thedatatypeofthevariable,and Valueofthevariable. Forbetterunderstanding,pleasehavealookatthefollowingimage.Here,wedeclareavariableoftypeintandassignavalue101. Theaboveimageshowsahigh-leveloverviewofwhathappeninginthememory.Butdependingonthedatatype(i.e.dependingonthevaluetypeandreferencetype),thememorymaybeallocatedeitherinthestackorintheheapmemory. UnderstandingStackandHeapMemoryinC#: Therearetwotypesofmemoryallocationforthevariablesthatwecreatedinthe.NETApplicationi.e.stackmemoryandheapmemory.Letusunderstandthestackandheapmemorywithanexample.Inordertounderstandstackandheap,pleasehavealookatthefollowingcode,andlet’sunderstandwhatactuallyhappensinthebelowcodeinternally. Asyoucanseeintheaboveimage,theSomeMethodhasthreestatements,let’sunderstandstatementbystatementhowthingsareexecutedinternally. Statement1: Whenthefirststatementisexecuted,thecompilerallocatessomememoryinthestack.Thestackmemoryisresponsibleforkeepingtrackoftherunningmemoryneededinyourapplication.Forbetterunderstanding,pleasehavealookatthefollowingimage. Statement2: Whenthesecondstatementisexecuted,itstacksthismemoryallocation(memoryallocationforvariabley)ontopofthefirstmemoryallocation(memoryallocationforvariablex).Youcanthinkaboutthestackasaseriesofplatesordishesputontopofeachother.Pleasehavealookatthefollowingdiagramforabetterunderstanding. TheStackMemoryallocationandde-allocationin.NETaredoneusingtheLastInFirstOutprinciple.Inotherwords,wecansaythatthememoryallocationandde-allocationaredoneonlyatoneendofthememory,i.e.,thetopofthestack. Statement3: Inthe3rdstatement,wehavecreatedanobjectofSomeClass.Whenthe3rdstatementisexecuted,itinternallycreatesapointeronthestackmemoryandtheactualobjectisstoredinadifferentmemorylocationcalledHeapmemory.Theheapmemorylocationdoesnottrackrunningmemory.Heapisusedfordynamicmemoryallocation.Forabetterunderstandingpleasehavealookatthebelowimage. Note:Thereferencepointersareallocatedonthestack.Thestatement,SomeClasscls1doesnotallocateanymemoryforaninstanceofSomeClass,itonlyallocatesavariablewiththenamecls1inthestackandsetsitsvaluetonull.Thetimeithitsthenewkeyword,itallocatesmemoryintheheap. Whathappenswhenthemethodcompletesitsexecution? Whenthethreestatementsareexecuted,thenthecontrolwillexistfromthemethod.Whenitpassestheendcontroli.e.theendcurlybrace“}”,itwillclearallthememoryvariableswhicharecreatedonthestack.Itwillde-allocatethememoryina‘LIFO’fashionfromthestack.Forabetterunderstandingpleasehavealookatthebelowimage. Itwillnotde-allocatetheheapmemory.Later,theheapmemorywillbede-allocatedbythegarbagecollector.Nowyoumayhaveonequestioninyourmindwhytwotypesofmemory,can’twejustallocateeverythingtojustonememorytype? Whydowehavetwotypesofmemory? Asweknow,inC#,theprimitivedatatypessuchasint,double,bool,etc.justholdasinglevalue.Ontheotherhand,thereferencedatatypesorobjectdatatypesarecomplexi.e.anobjectdatatypeorreferencedatatypecanhavereferencetootherobjectsaswellasotherprimitivedatatypes. So,thereferencedatatypeholdsreferencestoothermultiplevalues,andeachoneofthemmustbestoredinmemory.Objecttypesneeddynamicmemorywhileprimitivedatatypesneedstaticmemory.Pleasehavealookatthefollowingimageforabetterunderstanding. Valuetypesandreferencetypesin.NET AsweunderstoodtheconceptofStackandHeap,Now,letusmoveforwardandunderstandtheconceptvaluetypesandreferencetypesindetail.TheValuetypesarethetypesthatholdbothdataandmemoryinthesamelocation.Ontheotherhand,areferencetypeisatypethathasapointerthatpointstotheactualmemorylocation. UnderstandingValueTypeinC#: Letusunderstandvaluetypewithanexample.Pleasehavealookatthefollowingimage.Asyoucanseeintheimage,firstwecreateanintegervariablewiththenamexandthenweassignthisxintegervaluetoanotherintegervariablewhosenameisy.Inboththesememoryvaluesareallocatedonthestack. In.NET,whenweassignoneintegervariablevaluetoanotherintegervariable,thenitcreatesacompletelydifferentcopyinthestackmemorythat’swhatyoucanseeintheaboveimage.So,ifyouchangeonevariablevalue,thentheothervariablewillnotbeaffected.In.NETthesekindsofdatatypesarecalled‘Valuetypes’.So,bool,byte,char,decimal,double,enum,float,long,sbyte,int,short,ulong,struct,uint,ushortareexamplesofvaluetypes. UnderstandingReferenceTypeinC#: Letusunderstandreferencetypewithanexample.Pleasehavealookatthefollowingimage.Here,first,wecreateanobjecti.e.obj1)andthenassignthisobjecttoanotherobjecti.e.obj2.Inthiscase,bothreferencevariables(obj1andobj2)willpointtothesamememorylocation. Inthiscase,whenyouchangeoneofthem,theotherobjectisalsogetsaffected.Thesekindsofdatatypesaretermedas‘Referencetypes’in.NET.So,class,interface,object,string,anddelegateareexamplesofReferenceTypes. Howistheheapmemoryfreedup? Thememoryallocationwhichisdoneonthestackisgonewhenthecontrolmovesoutfromthemethodi.eoncethemethodcompletesitsexecution.Ontheotherhand,thememoryallocationwhichisdoneontheheapneedstobede-allocatedbythegarbagecollector. Whenanobjectstoredontheheapisnolongerused,thatmeanstheobjectdoesnothaveanyreferencepointing,thentheobjectiseligibleforgarbagecollection.Atsomepointintime,thegarbagecollectorwillde-allocatethisobjectfromtheheap. Inthenextarticle,IamgoingtodiscussBoxingandUnboxinginC#.NETwithExamples.Here,inthisarticle,ItrytoexplainStackandHeapMemoryinC#withExamples.IhopeyouenjoythisStackandHeapMemoryinC#withExamplesarticle.Iwouldliketohaveyourfeedback.Pleasepostyourfeedback,question,orcommentsaboutthisarticle. PreviousLesson Checked and Unchecked KeywordsinC# NextLesson BoxingandUnboxinginC# 15thoughtson“StackandHeapMemoryinC#” NiceexplanationsirReply Thankyouforfindingthisarticlehelpful.Reply muchmoreunderstandingReply Ilovethissite,eachandeverythingisexplainverywell.Alltopicarecoveredbythissitenoneedtogoanywherejustreaditcarefully.ThankstomakeitReply Thankyousomuch.Yourfeedbackmeansalotus.Reply Nicearticles.Iamveryeasytounderstandtheseconcepts.BoxingandUnboxinginthe.NETconceptaremissinginthenextarticle.pleasepostthisarticle.Reply Hi,Thankyouforyourfeedback.WewilladdtheBoxingandUnboxingtopicsverysoon.Reply Veryhelpful,verydetailedforinterviewpreparationReply Thankyousomuchforgivingyourvaluablefeedback.Reply NiceArticlesir…withaunderstandableexamplesReply Yourfeedbackmotivatesustowritesucharticlesindepth.Reply Niceexplanationsir,asasignofgratitude,Icanonlyclickonadssoyoucanbeevenmoreenthusiasticaboutmakingmorein-deptharticlesabout.net,ican’twaitthearticleaboutBoxingandUnboxingconceptin.net,thankyouverymuchReply Yourfeedbackisalotofmeanstous.Inthecomingdays,youwillseeBoxingandUnboxingarticlesalongwithallthemissingarticles.Currently,wearereworkingonthesetutorials.Reply Hi,thanksfornicetutorial.Iwouldliketoaddsomeinfoaboutvaluetypesandstack.Valuetypesareonlystoredonthestackiftheyarelocalvariablesinsideamethod,ortheirparameters.Thisiswhatthestackistherefor:storinglocalvariablesandparameters(andthereturnpointersoffunctioncalls).Ifthevaluetypewasdeclaredasavariableinsideamethodthenit’sstoredonthestack.Ifthevaluetypewasdeclaredasamethodparameterthenit’sstoredonthestack.Ifthevaluetypewasdeclaredasamemberofaclassthenit’sstoredontheheap,alongwithitsparent.Ifthevaluetypewasdeclaredasamemberofastructthenit’sstoredwhereverthatstructisstored.Reply HiBARNABAS.666,Thanksforyourvaluableinput.Peopleslikeyoumotivateustowritemoreandmorecontent..Reply LeaveaReplyCancelreplyYouremailaddresswillnotbepublished.Requiredfieldsaremarked*Comment*Name*Email*Website
延伸文章資訊
- 1Net 三種區塊記憶體位置Heap , Stack , Globle?? | 石頭的 ...
【C#】 Math.Round (128.5) = 128 真假四捨五入? 【C#】 AOP輕型框架AwesomeProxy.Net 介紹使用 · Struct V.S Class 兩者之間差異...
- 2Stack Vs Heap Memory - C#
Difference between Stack and Heap Memory in C# ; Contains, It contains values for Integral Types,...
- 3Understanding the Stack and Heap in C# | endjin
- 4Stack、Heap、Static | 阿猩的程式蛋糕店 - - 點部落
在C#中,實值型別存放在Stack,參考型別的話,Pointer會存在Stack,裡面可以是null或資料存放的記憶體位址,整個物件則存放在Heap中。
- 5C# Heap(ing) Vs Stack(ing) In .NET - Part One
The Stack is more or less responsible for keeping track of what's executing in our code (or what'...