Monday, December 20, 2010

C#.NET TUTORIAL 3:: STACK HEAP,METHODS,ENUM,READONLY,CONSTRUCTORS ,DESTRUCT,CONSTANTS

CONTENTS


1.  ACCESS MODIFIERS
2.  CONSTRUCTORS
          2.1 DECLARING A CONSTRUCTOR
3.  DESTRUCTORS
4.  METHODS
5. CONSTANTS
6. ENUMENRATION
7. READONLY
8.  STACK AND HEAP INTRODUCTION
9.  STATIC KEYWORD


   In this third tutorial of c#.net I am going to explain the concepts access modifiers which are used overall c# coding in classes, functions, properties, methods, interfaces etc.,

1. Access Modifiers
        An access modifier determines which class methods can be accessed within or outside the class. The C# access modifiers are as follows:
Access modifiers
Access Modifier       Restrictions
Public                       No restrictions. Members marked public are visible to any method of any class.
Private                      only accessible within the class
Protected                  within the class and derived class. within the or outside the assembly.
Internal                     within the class and within the assembly
Protected internal      within the class and derived classes but within the same assembly.

Example, the declarations of member variables should have been written as follows:
SYNTAX:    private <data type> <variable name>
                        Private int Year;
                        Private int Month;

2. Constructors
                  
    • Constructors are special methods of classes.
    • Constructor name and class name will be same
    • Constructors are not needed to call externally like functions
    • Constructors are invoked when the class memory is allotted
    • Constructors will not have return type or constructors will not return any value.
    • There are different types of constructors. They are :

1.      Default              : Each and every c# program will have one inbuilt constructor
2.      Parameterized   : Constructors with parameters or argument list
3.      Copy                  : A copy constructor creates a new object by copying variables from an
                             Existing object. Copy constructor should be parameterized constructor
4.      Static                 : Executes once in lifetime of class.



2.1 Declaring a constructor:   Syntax for declaring constructor is as follows:
         Public <class name>
{
//member declaration
//method declaration
}


Example program for constructor:


 Using System;
Using System.Collections.Generic;
Using System. Text;

Namespace constructors
{
    Class Program
    {
        Public class my circle
        {
                //constructors program
            Float radius;
            Const float pi = 3.14f;
            Float area;
            //this is constructor with the same class name
           Public my circle ()
           {
               Radius=10.0f;
               //pi = 3.14f;          
           }
            Public void calculate area ()
            {
                Area=pi*radius*radius;

            }
            Public void display ()
            {
                Console.WriteLine("area {0}", area);
                Console.Read();
            }
        }
        static void Main(string[] args)
        {
            mycircle circleobj = new mycircle();
            circleobj.calculatearea();
            circleobj.display();
        }
    }
}

Program for pramterized constructor example ::  
using System;
using System.Collections.Generic;
using System.Text;

namespace parameterizedconsturctor
{
    class Program
    {

        public class mycircle
        {
            //para metrized consturctors program
            float radius;
            const float pi = 3.14f;
            float area;
            //this is constuctor with the same class name but parametrized
            public mycircle(float r, float pivalue)
            {
                radius = r;
                pivalue = pi;
                Console.WriteLine("u arwe in 2 parametized construcotr");
            }
            public mycircle(float r)
            {
                Console.WriteLine("u arwe in single parametized construcotr");
                radius = r;
                //pi = 3.14f;
            }
            public void calculatearea()
            {
                area = pi * radius * radius;

            }
            public void display()
            {
                Console.WriteLine("area {0}", area);
                Console.Read();
            }
        }
        static void Main(string[] args)
        {
            mycircle c = new mycircle(10f, 3.14f);
            c.calculatearea();
            c.display();
            mycircle c1 = new mycircle(22);
            c1.calculatearea();
            c1.display();
        }
    }

}

3. The C# Destructor

C#'s destructor looks, syntactically, much like a C++ destructor, but it behaves quite differently.
You declare a C# destructor with a tilde as follows:
~MyClass( ){}
In C#, however, this syntax is simply a shortcut for declaring a Finalize( ) method that chains up
to its base class. Thus, writing:
~MyClass( )
{
// do work here
}

Sample program for destructor is as follows::::::::

using System;
using System.Collections.Generic;
using System.Text;

namespace destructors
{
    class Employee

   {
       
            int empno;
            string empname;
            float basic, hra, da, netsal;
        //constuctor is below the same name as class---------------------------------

     
        public Employee()
        {
           Console.WriteLine("enter employee details:::::::");
            Console.WriteLine("employee number");
            empno =int.Parse(Console.ReadLine());
            Console.WriteLine("employee name");
            empname = Console.ReadLine();
             Console.WriteLine("employee basic salary");
            basic=float.Parse(Console.ReadLine());
            Console.WriteLine("employee hra");
            hra = float.Parse(Console.ReadLine());
            Console.WriteLine("employee percentage in between 10 to 20 of da");
            da = float.Parse(Console.ReadLine());
        }
        /// <summary>
        /// destructor
        /// </summary>
        ~Employee()
        {
            Console.WriteLine("memory destructed");
            Console.Read();
        }
        public void calculate()
        {
            da = (basic * da) / 100;
            netsal = basic + da + hra;
           
        }
        public void display()
        {
            Console.WriteLine("enter employee details:::::::");
            Console.WriteLine("number {0}\n name {1}\n basic {2}\n da {3}\n hra {4}\n netsalay {5}", empno, empname, basic, da, hra, netsal);
            Console.Read();
        }
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            emp.calculate();
            emp.display();
        }
    }
}

4. Methods
  • A class has both properties and behaviors. Behaviors are defined with member methods;
  • A method is a function owned by your class. In fact, member methods are sometimes called memberfunctions.
  • The member methods define what your class can do or how it behaves.
  • To declare a method, you specify a return value type followed by a name. Method declarations also require parentheses, whether the method accepts parameters or not.
  •  For example: int my Method(int size );
  • declares a method named my Method that takes one parameter: an integer which will be referred to
  • Within the method as size. My method returns an integer value.




5. Constants
A constant is a variable whose value cannot be changed. Variables are a powerful tool, but there are times when you want to manipulate a defined value, one whose value you want to ensure remains constant.

You declare a symbolic constant using the
const keyword and the following syntax:
const type identifier = value;
A constant must be initialized when it is declared, and once initialized it cannot be altered

Sample consonants program is as follows::


using System;
using System.Collections.Generic;
using System.Text;

namespace constants
{
 
    class Program
    {
       //public read-only int a;
       
        public static void Main(string[] args)
        {
            int I;
            I = 12;
          
         
            const int Freezing Point = 32;-----------here consonant declared
            //Console.WriteLine("enter the read-only integer value");
           // a=int.Parse(Console.ReadLine);
          
            I = Freezing Point + 12;
            Console.WriteLine("value of variable I {0}", I);
            Console.WriteLine("Freezing point of water: {0}", Freezing Point);
            Console.ReadLine();
        }
    }
}


6. Enumerations
Enumerations provide a powerful alternative to constants. An enumeration is a distinct value type,
consisting of a set of named constants (called the enumerator list).


The technical definition of an enumeration is:
[attributes] [modifiers] enema identifier
[:base-type] {enumerator-list};


enum Temperatures
{
WickedCold = 0,
FreezingPoint = 32,
LightJacketWeather = 60,
SwimmingWeather = 72,
BoilingPoint = 212
}

Sample program for enum datatype is as follows ::::::::
using System;
using System.Collections.Generic;
using System.Text;

namespace enumerationdatatype
{
    enum weekday
    {
        monday,
        tuesday,
        wednesday,
        thursday,
        friday,
        saturday,
        sunday
    }

    enum colors
    {
        red, green, black
    }
   
    class Program
    {
        static void Main(string[] args)
        {
            weekday w;
            w=weekday.friday;
            w = weekday.saturday;
            Console.WriteLine(w);

            ////colors enum
            //   Console.WriteLine("black {0}", (colors.black));
            //display the value of the color from enum by convert.toint32 funciton
               Console.WriteLine("black {0}", (Convert.ToInt32(colors.green)));

            Console.Read();
        }
    }
}



7. Read only

it is same as constant but for constant we should assign value at declaration and for read-only we can assign value at runtime.

Read-only float p;




8. The Stack and the Heap
A stack is a data structure used to store items on a last-in first-out basis (like a stack of
dishes at the buffet line in a restaurant). The stack refers to an area of memory supported
by the processor, on which the local variables are stored.
In C#, value types (e.g., integers) are allocated on the stack—an area of memory is set
aside for their value, and this area is referred to by the name of the variable.
Reference types (e.g., objects) are allocated on the heap. When an object is allocated on
the heap its address is returned, and that address is assigned to a reference.
The garbage collector destroys objects on the stack sometime after the stack frame they
are declared within ends. Typically a stack frame is defined by a function. Thus, if you
declare a local variable within a function the object will be marked for garbage collection after the function ends. Objects on the heap are garbage collected sometime after the final reference to them.

9. static
class Hello World
{
static void Main( )
{
// Use the system console object
System.Console.WriteLine("Hello World");
}
The Main( ) method shown in Example above has one more designation. Just before the return type
declaration void (which, you will remember, indicates that the method does not return a value)
you'll find the keyword static:
static void Main( )
The static keyword indicates that you can invoke Main( )without first creating an object of type Hello.
}



 -----------------------------THE END----------------------------