Stack and Heap Memory in C# with Examples - Dot Net Tutorials

文章推薦指數: 80 %
投票人數:10人

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



請為這篇文章評分?