Monday, September 17, 2018

Stack & Heap Memory

Stack & Heap Memory:

           When we declare a variable in a .NET application, it allocates some space of memory in the RAM. This memory has three things: the name of the variable, the data type of the variable, and the value of the variable.
That was a simple explanation of what happens in the memory, but depending on the data type, your variable is allocated that type of memory. The Common Language Runtime (CLR) automatically handles Memory Management with the help of its components. The Garbage Collector plays an important role in Memory Management. Objects are automatically freed when they are no longer needed by the application by Garbage Collector.

There are two types of memory allocation: stack memory and heap memory.

Stack Memory:

            The stack is used for static memory allocation. It is an array of memory. Think of the stack as a series of boxes stacked one on top of the next. It is a Last-in, First-out (LIFO) data structure. Data can be added to and deleted only from the top of the stack. Placing a data item at the top of the stack is called pushing the item onto the stack. Deleting an item from the top of the stack is called popping the item from the stack. Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it's allocation is done when the program is compiled. The stack is responsible for keeping track of the running memory needed in your application. The stack contains value type data. Mostly stack contains local variables which visible only to owner thread & gets cleared once they lost the scope.

Heap Memory:

The Heap is used for dynamic memory allocation. Unlike the stack, data can be stored and removed from the heap in any order. Your program can store items in the heap, it cannot explicitly delete them.  Variables allocated on the heap have their memory allocated at run time and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory. The heap contains reference types. The heap memory is used by all part of application thus objects created on heap visible to all threads. Allocation & de allocation of heap memory is done by Garbage Collector.

For Example:

public void Method1()
{
    // Line 1
    int i=6;

    // Line 2
    int y=8;

    //Line 3
    class1 cls1 = new class1();
}

It’s a three line code, let’s understand line by line:

Line 1:  When line 1 is executed, the compiler allocates a small amount of memory in the stack. The stack is responsible for keeping track of the running memory needed in your application.

Line 2: At line 2 memory allocates on top of the first memory allocation. You can think about stack as a series of compartments or boxes put on top of each other. Memory is allocated and de-allocated at only one end of the memory, i.e., top of the stack.

Line 3: In line 3, we have created an object. When this line is executed it creates a pointer on the stack and the actual object is stored in a different type of memory location called ‘Heap’. ‘Heap’ does not track running memory, it’s just a pile of objects which can be reached at any moment of time. Heap is used for dynamic memory allocation.

Difference between Stack and Heap Memory:


Friday, September 14, 2018

Command Line Argument

Command Line Argument:

It is possible to pass some values from the command line to your C# programs when they are executed. The arguments can be used as input for the program. A parameter supplied to the program through the command line is when it invoked is called Command Line Argument. We can pass any number of arguments from the command prompt. The Main() method is entry point method for a program. Command line arguments are passed to the Main() method.
In C# Main() method can be declared with the String[] args parameter. The args parameter accepts command-line arguments which can be used to provide the program some values at the moment of execution. The args argument is array of type String. The program accept arguments in the order of args[0], args[1] and so on. The arguments are separated by white space, i.e. either space or tab.

For Example:
using System;
class Sample
{
            static void Main(string[] args)
            {
                        int SUM         = 0;
                        int X   = 0;
                        int Y   = 0;

                        X = Convert.ToInt32(args[0]);        // Command Line Argument 1
                        Y = Convert.ToInt32(args[1]);        // Command Line Argument 2

                        SUM = X + Y;
                        Console.WriteLine("Sum is: "+SUM);                 
            }
}

To Compile:
csc sample.cs

To Execute: 









                    Here, we are passing 10 and 20 as command line arguments which can be accessed through args. Where 10 will be assigned into args[0] and 20 will be assigned into args[1].

Entry Point Method Main

Entry Point Method:

In computer programming, an entry point is where control is transferred from the operating system to a computer program, at which place the processor enters a program or a code fragment and execution begins. The Main() method is the entry point of a C# console application or windows application. It is the starting point of execution of an application. When the application is started, the Main() method is the first method that is invoked. There can only be one entry point in a C# program. The Main() is declared inside a class. The Main() must be static. The Main() can either have a void or int as return type. The Main method can be declared with or without a string[] parameter that contains command-line arguments.

Syntax :-
public static void/int Main(String []args)
{
               -------------------
               -------------------
}

public:
Accessibility of a method is specified by access modifier. public is the access modifier of the main method that implies that the method is accessible from all other methods. The Main() method should be accessible to everyone. It has to be public so that .Net runtime can execute this method from outside the class. Remember that if you make any method non-public then it’s not allowed to be executed by any program. So it means that the main method has to be public.

static:
When program execution starts, there is no object of the class present. The Main method instantiates other objects and variables but there is no any method there that can instantiate the main method in C#. Static members are scoped to the class level, rather than the object level. Static members can be invoked without creating new class object. As main method is the entry point of the program it runs without creating an instance of the class. If the main method won’t be static, the runtime environment would not be able to call it because there is no object of the class is present.

void/int:
Every method must have a return type. In C# it is void or int. When it declare as void Main() does not return a value. Some time we can declare as int when it is declare as int operating system waits for return a value.

String []args:
            The Main method can be declared with or without a parameter. The String []args is array of string which is used as parameter. Sometime program needs to receive some arguments when execution stars. These arguments are called as command line argument. The String []args receives the command line arguments. It accepts only string type of argument and stores it in a string array.  

Valid forms of Main in C#:
There are four different ways to declare main method in C#.

1. public static void Main():
            This form of Main() will not return anything as it’s return type is void. It also not receives any command line argument.  

2. public static int Main():
             This form of Main() will returns integer value as it’s return type is int. An operating system waits for return a value. It will not receive any command line argument.

3. public static void Main( String []args):
            This form of Main() will not return anything as it’s return type is void. It will receives command line arguments in String []args.

4. public static int Main( String []args):
           This form of Main() will return integer to operating system as it’s return type is int. It will receives command line arguments in String []args.

Introduction to C# Programming

Introduction to C#:
In 2000, Microsoft announced the C# programming language. C# is designed to be a simple, modern, general-purpose, object-oriented programming language, borrowing key concepts from several other languages. C# has roots in C, C++ and Java. C# has similar capabilities to Java and is appropriate for the most demanding app-development tasks, especially for building today’s large-scale enterprise apps, web-based, mobile and “cloud”-based apps. C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework.

C# is object oriented and has access to the powerful .NET Framework Class Library—a vast collection of prebuilt classes that enable you to develop apps quickly. C# is event driven programming language. You’ll write programs that respond to user-initiated events such as mouse clicks, keystrokes, timer expirations, touches and finger swipes—gestures that are widely used on smart phones and tablets. C# also allows asynchronous programming in which multiple tasks can be performed at the same time. Asynchronous make your apps more responsive to user interactions, such as mouse clicks and keystrokes, among many other uses.

The following reasons make C# a widely used professional language:
  • It is a modern, general-purpose programming language
  • It is object oriented.
  • It is component oriented.
  • It is easy to learn.
  • It is a structured language.
  • It produces efficient programs.
  • It can be compiled on a variety of computer platforms.
  • It is a part of .Net Framework.
Programming Features of C# Language:
  • Boolean Conditions
  • Automatic Garbage Collection
  • Standard Library    Assembly Versioning
  • Properties and Events
  • Delegates and Events Management
  • Easy-to-use Generics
  • Indexers
  • Conditional Compilation
  • Simple Multithreading
  • LINQ and Lambda Expressions
  • Integration with Windows