Dotnetfreaks' Blog | C#

Dotnetfreaks' Blog

Fabulous Adventures In DotNet

About the author

Author Name is someone.
E-mail me Send mail

Recent posts

Recent comments

Archive

Tags

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012

Memory in .NET - (Vagueness Of .NET Memory Management)


Couple of days ago i met with a .net guru and we had discussion on advanced concept of .NET and Memory management; I am sharing the findings of that discussion with you. I feel that many .NET programmers still do not realize the difference between Primitive, Reference and Value types, and how they stored in memory (what goes where) and misuse of any type can lead to subtle bugs that are very hard to find. So it is very important to understand the different types that .NET Framework supports. In this article, I am going to talk about these different types briefly. 
 
"Variables" are simply storage locations for data becuase it is really hard to pragramme against the memory address. It means, a variable is just an association between a name and memory slot. You can place data into them and retrieve their contents as part of a C# expression. The size of that slot, and the interpretation of the value is controlled through "Types" - and this is where the difference between value types and reference types comes in.

Primitive types

 Any data types directly supported by the compiler are called primitive types. Primitive types map directly to types that exist in the base class library. For example, in C# an int maps directly to the System.Int32 type. Because of this, the following two lines of code are identical to the two lines of code shown previously:

System.Int32 a = new System.Int32(5);
System.Int32 a = 5; 
Above lines are identical to following lines:
 
int a = new int(5);
int a = 5;

Value Types

 A data type is a value type if it holds the data within its own memory allocation. Value types derive from System.ValueType, which derives from System.Object. Types that derive from System.ValueType have special behavior in the CLR. Value type variables directly contain their values, which means that the memory is allocated inline in whatever context the variable is declared. There is no separate heap allocation or garbage collection overhead for value-type variables. Value types include the following:
  • All numeric data types
  • Boolean, Char, and Date
  • All structures, even if their members are reference types
  • Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong
Every structure is a value type, even if it contains reference type members. For this reason, value types such as Char and Integer are implemented by .NET Framework structures.
You can declare a value type by using the reserved keyword, for example, Decimal. You can also use the New keyword to initialize a value type. This is especially useful if the type has a constructor that takes parameters. An example of this is the Decimal(Int32, Int32, Int32, Boolean, Byte) constructor, which builds a new Decimal value from the supplied parts.
public struct TestStruct
{
    public int x, y;

    public TestStruct(int p1, int p2)
    {
        x = p1;
        y = p2;
    }
}
Value types are sealed, which means, for example, that you cannot derive a type from System.Int32, and you cannot define a struct to inherit from any user-defined class or struct because a struct can only inherit from System.ValueType. However, a struct can implement one or more interfaces. You can cast a struct type to an interface type; this causes a boxing operation to wrap the struct inside a reference type object on the managed heap. Boxing operations occur when you pass a value type to a method that takes a System.Object as an input parameter. 

Reference Types

A reference type contains a pointer to another memory location that holds the data. Reference types include the following:
  • String
  • All arrays, even if their elements are value types
  • Class types, such as Form
  • Delegates
A class is a reference type. For this reason, reference types such as Object and String are supported by .NET Framework classes.
 
Note that every array is a reference type, even if its members are value types.
 
Since every reference type represents an underlying .NET Framework class, you must use the New Operator (Visual Basic) keyword when you initialize it. The following statement initializes an array. The value of a reference type variable is always either a reference or null. If it's a reference, it must be a reference to an object which is compatible with the type of the variable. The slot of memory associated with the variable is just the size of a reference, however big the actual object it refers to might be. (On the 32-bit version of .NET, for instance, a reference type variable's slot is always just 4 bytes.)

Elements That Are Not Types

The following programming elements do not qualify as types, because you cannot specify any of them as a data type for a declared element:
  • Namespaces
  • Modules
  • Events
  • Properties and procedures
  • Variables, constants, and fields  

So where are things stored?

The memory slot for a variable is stored on either the stack or the heap. It depends on the context in which it is declared:
  • Each local variable (ie one declared in a method) is stored on the stack. That includes reference type variables - the variable itself is on the stack, but remember that the value of a reference type variable is only a reference (or null), not the object itself. Method parameters count as local variables too, but if they are declared with the ref modifier, they don't get their own slot, but share a slot with the variable used in the calling code.
  • Instance variables for a reference type are always on the heap. That's where the object itself "lives".
  • Instance variables for a value type are stored in the same context as the variable that declares the value type. The memory slot for the instance effectively contains the slots for each field within the instance. That means (given the previous two points) that a struct variable declared within a method will always be on the stack, whereas a struct variable which is an instance field of a class will be on the heap.
  • Every static variable is stored on the heap, regardless of whether it's declared within a reference type or a value type. There is only one slot in total no matter how many instances are created. (There don't need to be any instances created for that one slot to exist though.)
There are a couple of exceptions to the above rules - captured variables (used in anonymous methods and lambda expressions) are local in terms of the C# code, but end up being compiled into instance variables in a type associated with the delegate created by the anonymous method. The same goes for local variables in an iterator block.



Happy reading...........
 



Posted by Ajander Singh on Tuesday, November 29, 2011 3:09 PM
Permalink | Comments (2) | Post RSSRSS comment feed

C# Partial Classes and Methods


 

One of the unique features of C# is the concept of Partial, extendable to definition of a Class or a Struct, an Interface or a method.
Using this, the definition of any class, struct, interface of method can exist in two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.

To split a class definition, partial keyword modifier is used.

For Example:

   1:      public partial class Pradeep
   2:      {
   3:          public void OnLeave()
   4:          {
   5:          }
   6:      }
   7:   
   8:      public partial class Pradeep
   9:      {
  10:          public void InMeeting()
  11:          {
  12:          }
  13:      }

Here, it is valid to use the same name for the class and implement desired functionality separately.
Finally, when compiled, the code is auto merged , giving a Final class named Pradeep, with the two methods that were defined separately.

The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace.
Following are the points that need to be taken care of while working with Partial keyword.

  • All the parts must use the partial keyword.
  • All the parts must have the same accessibility, such as public, private, and so on.
  • All partial-type definitions meant to be parts of the same type must be defined in the same assembly and the same module (.exe or .dll file). Partial definitions cannot span multiple modules.
  • If any part is declared abstract, then the whole type is considered abstract.
  • If any part is declared sealed, then the whole type is considered sealed.
  • If any part declares a base type, then the whole type inherits that class.
  • Parts can specify different base interfaces, and the final type implements all the interfaces listed by all the partial declarations.
  • Nested types can be partial, even if the type they are nested within is not partial itself

For Example:

    class LeaveReachTimings
    {
        partial class Residence
        {
            void TimetoReach() { }
        }
        partial class Office
        {
            void TimeToLeave() { }
        }
    }


Here the Class LeaveReachTimings is not partial, but it is completely valid to declare partial classes Residence and Office as nested classes in it.

  • Attributes of partial-type definitions are merged

For Example

    [SerializableAttribute]
    partial class CurrentCompany { }

    [Obsolete Attribute]
    partial class CurrentCompany { }

    These two attributes will finally merge and are equivalent to the following.

    [SerializableAttribute]
    [Obsolete Attribute]
    partial class CurrentCompany { }

Enough of Theory Let us now create one partial Class to verify the concepts covered so far.

Partial Class:

 

    public partial class Record
    {
        private int x;
        private int y;

        public Record(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }

    public partial class Record
    {
        public int PrintSum()
        {
            return x + y;
        }

    }

 
Partial Methods:

Similar to Partial Classes, Partial Methods are also allowed. These are allowed in partial classes or struct.
One part of class contains the signature and the same or other part of the partial class can contain its implementation.
If no implementation is provided, then the method and all calls made to it are removed at compile time.

Therefore, any code in the partial class can use a partial method, even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented.

A partial method declaration consists of two parts: the definition, and the implementation. These may be in separate parts of a partial class, or in the same part.

If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method.

Following are the considerations with Partial Methods.

  • Partial method declarations must begin with the partial keyword
  • Return Type is always void.
  • out parameters are not allowed , however ref can be used.
  • Partial methods cannot be virtual as they are implicitly private.

It means they have access modifiers such as public, private or internal. Hence, they cannot be called from outside the partial class, and cannot be declared as virtual.

  • Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.
  • Partial methods can use static and unsafe modifiers.
  • Partial methods can be generic.
  • A delegate to a partial method which has an implementation, can be made. But, the partial method which has just a signature and no implementation can not have a delegate.


Example:

    public partial class PartialClassTest
    {
        private string mytest = string.Empty;

        partial void MyPartialMethodTest();

    }


    public partial class PartialClassTest
    {
        partial void MyPartialMethodTest()
        {
            mytest = "Partial Method call Succeded!!";

        }

        public string returnstring()
        {
            MyPartialMethodTest();
            return mytest;

        }
    }

Here the partial methods, always return void and to get the value of mytest string I have to declare yet another method(return string), which finally prints the string on the webpage if called as per the following code.

    protected void Page_Load(object sender, EventArgs e)
    {
        PartialClassTest ptest = new PartialClassTest();
        Response.Write(ptest.returnstring());
    }

Please note: Delegate or Enumeration declarations can not use partial keyword.

Hope this discussion was helpful.

Till Next time we connect, Happy Coding!!!




Posted by Pradeep Patel on Thursday, June 10, 2010 7:05 PM
Permalink | Comments (0) | Post RSSRSS comment feed

CLR VIA c# 3rd edition PDF


 

About The Book
Get expert guidance to exploit CLR capabilities and the Microsoft .NET Framework 4.0.

 

Dig deep and master the intricacies of the common language runtime (CLR) and the .NET Framework 4.0. Written by a highly regarded programming expert and consultant to the Microsoft .NET team, this guide is ideal for developers building any kind of application—including Microsoft ASP.NET, Windows® Forms, Microsoft SQL Server®, Web services, and console applications. You’ll get hands-on instruction and extensive C# code samples to help you tackle the tough topics and develop high-performance applications.

CLR VIA C# Jeffrey Richter

About the Author: Jeffrey Richter

Dig deep and master the intricacies of the common language runtime (CLR) and the .NET Framework 4.0. Written by a highly regarded programming expert and consultant to the Microsoft® .NET team, this guide is ideal for developers building any kind of application-including Microsoft® ASP.NET, Windows® Forms, Microsoft® SQL Server®, Web services, and console applications. You’ll get hands-on instruction and extensive C# code samples to help you tackle the tough topics and develop high-performance applications. It is October 2009 as I write this text, making it 10 years now that I’ve worked with the .NET Framework and C#. Over the 10 years, I have built all kinds of applications and, as a consultant to Microsoft, have contributed quite a bit to the .NET Framework itself. As a partner in my own company, Wintellect (http://Wintellect.com), I have worked with numerous customers to help them design software, debug software, performance-tune software, and solve issues they have with the .NET Framework. All these experiences have really helped me learn the spots that people have trouble with when trying to be productive with the .NET Framework. I have tried to sprinkle knowledge from these experiences through all the topics presented in this book.

Information gathered from Microsoft Site or log on to http://www.microsoft.com/learning/en/us/books.aspx?ID=13874&Locale=en-us

Publisher: Microsoft Press | ISBN: 0735627045 | Feb 2010 | PDF | 896 pages | 18.6 Mb

Download: Here




Posted by Ajander Singh on Sunday, May 02, 2010 6:59 PM
Permalink | Comments (0) | Post RSSRSS comment feed