Memory Management in C#

C# automatically manages memory so that developers are freed to worry about memory management.  In early days of C and C++, manual memory management requires us to write code to allocate and de-allocate memory blocks.

Automatic memory management does not only increase code quality but it also increases productivity. Developers focus on functional aspects rather than internals. 
Take following example of Stack class,

 

public class Stack

    {

        private Node first = null;

        public bool Empty

        {

            get

            {

                return (first == null);

            }

        }

        public object Pop()

        {

            if (first == null)

                throw new Exception(“Can’t Pop from an empty Stack.”);

            else

            {

                object temp = first.Value;

                first = first.Next;

                return temp;

            }

        }

        public void Push(object o)

        {

            first = new Node(o, first);

        }

        class Node

        {

            public Node Next;

            public object Value;

            public Node(object value) : this(value, null) { }

            public Node(object value, Node next)

            {

                Next = next;

                Value = value;

            }

        }

    } 

 

Here, Node instances are created in Push method and GC collects them, when they are not referenced.

Another example would be,

class Test

    {

        static void Main()

        {

            Stack s = new Stack();

            for (int i = 0; i < 10; i++)

                s.Push(i);

            s = null;

        }

    }

Here, we create an instance of Stack 10 times and then assign null value. As soon as instance is assigned with null value, it’s eligible for garbage collection (GC). Although, it’s unpredictable when garbage collector will run, but as a C# developer we don’t need to worry about it.

 

Leave a Comment

Reference Type and Value Type

Common Language Runtime is based on two types which are Reference Type and Value Type. Let’s take a brief look into each of one.

Reference Type

Most of Microsoft .net framework classes are reference types. So, what Reference Type is exactly?

It is a type which is always allocated from the managed heap.

You need to use C# new keyword to allocate them. This “new” keyword returns memory address of this reference type object.

Most of people don’t know that declaring a reference type could force garbage collection to occur. As a programmer you should always prefer to use Value type over Reference types. All classes are Reference types like System.Exception, System.Random and they inherit from System.Object.

Value Type

It is type which is always allocated on thread’s stack.

The instance or variable contains the value rather than holding pointer to an instance. Most people get confused with enum and consider them reference type which is wrong. Structures and Enumerations are always value types, for example, System.Int, System.Boolean.

Important thing to note that all Value types are sealed which prevent them from being used as base type. In simple words, you cannot define a new type using Char, Int32 and Decimal etc. By default, C# compiler initializes value types by zero.

Comments (3)

ASP.NET Text Button Trick

Wrapping a text on a button is hard and there is an easy solution to it.

You can use &#13 carriage return in button text to display long text. For example, you want to display “Click here to apply for a loan application” and maximum length of the button can be only 30 characters. On button text property you will set “Click here to apply &#13 for a loan application”.

Now you can use carriage return character to display without cutting it off.

Comments (1)

InfoPath Logic Inspector


InfoPath Logic Inspector

InfoPath allows you to add data validation, calculate default values and rules to your form templates. This enables you to build very complex forms in a short amount of time. But there are some questions arise like how do you determine what data validation, calculated default values and rules are included in form? InfoPath helps you the data validation and rules evaluation process easier with Logic Inspector which you can use it in design mode.
Logic Inspector allows you to view all logic in your form template or for a specific field or a group in data source quickly. It will show you dependencies between different fields or groups in the form template.

Let consider an example, you have specified a calculated default value for a text box control which is bound to data field named Age. This default value is 21 with the name the user enters in another text box that is bound to field called Name. The logic inspector will show you that calculated default value for the Age field depends on the values entered in the Name field. If you delete the Name field and then find out that value for Age is not working correctly, you can look at the logic inspector to find out.

  

Let’s take a look at the logic inspector to see what it can tell us about logic in the form template. In design mode, click on Tools menu and then click on Logic Inspector menu item. Logic inspector is composed of four section named,

  • Data Validation
  • Calculated Default Values
  • Rules
  • Programming 

Leave a Comment

ASP.NET File Types

ASP.NET applications can include many types of files.

Following are details,

ASPX:
These are ASP.net web pages. They contain the user interface and in some cases underlying application code. Users request or navigate directly to one of these pages to start web application.

ASCX:
These are ASP.NET user controls. User controls are similar to web pages, except that the user can’t access these files directly. Instead, they must be hosted inside an ASP.NET web page. User controls allow  you to develop a small piece of user interface and reuse it in as many web forms as you want without repetitive code.

ASMX:
These are the ASP.NET web services which contain collections of methods that can be called over the internet. Web services work differently than web pages, but they still share the same application resources, configuration settings and memory.

CONFIG:
This is the XML based configuration file for your ASP.NET application. It includes settings for customizing security, state management, memory management, and much more.

ASAX:
This is the global application file. You can use this file to define global variables( variables that can be accessed from any web page in the web application) and react to global events (such as session start, application end).

Comments (1)

Visual Studio Tricks 1001

 

  • How to Add XML Comments

Type “///” three forward-slashes in front of class definition, method or property. Visual Studio automatically creates a XML formatted segment for you. You just need to provide description. Note: These comments are being used by VS.net to display information in intellisense.

  • Insert TODO

Sometimes you write some comments as a reminder of a task like code review, missing functionality, testing. VS.net gives you a power to insert TODO or comment tokens which gets compiled and VS.net organizes them in a list. Write “TODO:” infront of normal comments. For example,

/// TODO: Code review required.
foreach( string str in objList )
{
      // …
}

Select View > Show Tasks > All from menu to see list of TODO comments.

Note: In C#, VS.net will open display TODO’s from currently open files. Where as in case of VB.net, you will see TODO’s in the entire solution.

 

Leave a Comment