Tuesday 27 May 2014

Interface and its Importance

Inheritance is way or technique by using one class can access details of other class. What happen if you wants to access details of  more than one class and implement them with in current class.
C# cannot have more than one super-class. We can only do this by using Interface.

             class class-name : A, B , C
             {
                 // here  detail of implementation
                // A, B , C is other classes
              }  
above is not allowed in C#

We also know that C# not support multiple inheritance because by using this it create problems for developer but also create a lot of  confusion. To overcome with this issue C# support multiple inheritance by using Interface.

 An Interface in C# is reference type. There is some major different between class and interface.
  • Interface members can not be declared static.
  • Interface can not declared constructor and destructors.
  • All members of an Interface default public and abstract.
  • Interface methods are abstract so they do not include implementation of the method. 

Structure of Interface:

 An Interface only define the methods, properties, indexers and events but  not their implementation. It is the responsibility of that class that implements the interface.

         Interface name-of-interface
        {
                 // methods are here to go..
        }
    
(A)
             Interface first-interface
              {
                   int Addition( int x, int y);
              }

(B)
                          
              Interface Second-interface
              {
                   int  Multiple( int a, int b);
              }

In first interface only one method Addition and in second interface also one method Multiple.  

(C)
                Interface Third-interface
                {
                     int Divide ( int c, int d) ;
                 }
What happen if third interface inherit both of the A , B interface


    Interface Third-interface :  first-interface ,  Second-interface
     {
        int Divide ( int c, int d) ;
     }

Now, if any class inherit Third-interface then it automatically inherit both of the two interfaces( first-interface ,  Second-interface), and it is the responsibility of the class to implement their methods, otherwise it raise error.

Class Access-Interfacefirst-interface ,  Second-interface ,
Third-interface
 {
          //Implementation here
  }


Name Collision with Interface: 

What happen when you inherit multiple interfaces and some where two or more interface has common method name. It raises a voice of error, C# come out in this situation with explicit interface implementation.

Exp:

Interface A { void Name () };

Interface B { void Name () };

Class Access-Interface : A, B 
{
 public void Name(  ) { } ; // which method implement here A or B
}
   
with this technique explicit interface implementation we access method by using name of the interface.

Interface A{
   void Name( );
}

Interface B {
    void Name ( ) ;
}

Class AccessInterface :  A , B
{
      void A.Name( )
       { 
            Console.writeline("Interface A method call "); 
       }

       void B.Name ( )
      {
              Console.writeline("Interface B method call "); 
       }
}



Inheritance and Polymorphism

The main focus of OOP programming language is reducing to write code again and again. Is it possible; once you write a code and you can call that it anywhere in your program whenever you required.
Yes, you can do this type of work and it's power of OOP programming language.   Once you create a class and define some methods over there then you can call this class inside of other class and use its methods or properties.  This mechanism of designing or constructing one class form another class is called Inheritance.


What is Inheritance : When ever one class  wants to access properties,  methods of another class or to modify methods of another class or implement methods inside, it can possible only because of  Inheritance . 

Type of Inheritance: 
  1. Single inheritance
  2.  Multiple inheritance
  3. Hierarchical inheritance
  4. Multilevel inheritance
Role of visibility in Inheritance

 I think before understand Inheritance we should understand visibility and its importance. As it name automatically say a lot about itself, but we can say visibility is a technique by using you can access of one method into another class. 
 We can define visibility in two way :
  1. Class Visibility
  2. Methods Visibility
 Class Visibility: When you declared any class with the keyword Public or Internal , it automatically set the visibility of the class.
 Methods Visibility: Method visibility set with the keyword public , private, protected and etc...

Base Class Constructors :
Constructors are come in picture when we want to put values to the data fields of the class. constructor invoked when we create the object of the class. constructor are different types and in OOP programming language its huge impact in the program.
When one class inherit another class ( B inherit class A), and we wants to create object of class B. is it possible the same time we call of constructor of class A without create its object. Yes! we can, then the Base class constructors comes in the picture.

Exp:

 Class
{
         public int a;
         public int b;
                   public A (int x, int y)   // constructor for class A
                   {
                         a= x;
                         b= y;
                    }
        public int ADD( )    // addition method here
       {
               return ( a + b) ;
       }
}

Class B : A     //  inherit class A
{
     
    int c;
            public B ( int x, int y, int z) : base(x ,y)
            {
                    c=z;
            }
// note base keyword used here for calling class A constructor inside class B. first two values (x,y) put  in base( x,y) which call base class constructor and put values in a, b


      public Multiple( )  // Multiple method here
      {
         return (c * a* b);
     
      }





When you create the object of class B with the values, same time base class constructor all and initialize values of class A data fields.

* Note: base class constructor call before the derived class constructor. 

Saturday 24 May 2014

Classes and Objects


Classes create objects and objects use methods to communicate between them. We also know this technique as OOP.

BASIC PRINCIPLES OF OOP

All object oriented languages employ three core principles :
  • Inheritance
  • Polymorphism
  • Encapsulation
These are commonly known as three 'pillars' of OOP


Inheritance:

Inheritance is the concept we use to build new calsses using the existing class definitions. Through inheritance we can modify a class the way want to create new objects. The original class is know as base or parent class and the modified one is know as derived class or sub class or child class.
The concept of inheritance facilitates the re-usability of existing code and thus improves the integrity of programs and productivity of programmers.

Polymorphism:

In simple words it is the ability to take more than one form. For example, an operation may exhibit  different behaviour in different situations. The behaviour depends upon the types of data used in the operations. Exp:- an addition operation involving two numeric values will produce a sum and the same addition operation will produce a string if the operands are string values instead of numbers. Similarly, a method when called with one set of parameters may draw a circle but when called with another set of parameters may draw triangle.
Polymorphism is extensively use while implementing inheritance.

Encapsulation:

Encapsulation provides the ability to hide the internal details of an object from its users. The outside user may not be able to change the state of an object directly. However, the state of an object  may be altered indirectly using what are know as accessor and mutator methods.   In C#, encapsulation is implemented using the access modifier keywords public, private and protected. 


DEFINING A CLASS: 

you can say Class is a template of user defined data type with a template that serves to define its properties. Inside the calss wec define variable and  methods, these variables are termed as instances of classes, which are the actual objects.
The basic form of class is:
Class Name-of-the-class
{
    //here you declare variable
   // & methods
}
A class may contains properties, indexers, constructors, destructors and operators. 
 Adding Variables in Class:
 Class FirstClass   // name of the class
{
       int ABC;
       String DEF;
}
Here I declare class name <<FirstClass>> and inside the calss declare two variable one is integer type ABC and another one is String type DEF

 Adding Methods in Class:

There is no such use of datatype inside of the class without define Methods. If we create the object of the class having none method then the class cannot respond to any messages. Methods are declared inside the body of the class, usually after the declaration of instance variables. 

Example:
                type methodname  (parameter-list)
                {
                       // method body here
                 }

 The body actually describes the operations to be performed on the data. 

Class A
{
     int length;
     int width;

    public void Getdata(int x, int y) 

     {
           length= x;
           width= y;

      }

}

  Method Getdata its return type is void because it does not return any value. We pass two integer values x, y and the these value assign to local variables length and width
One more point to consider here that we use keyword public here when define method Getdata. In simple words if we wants to access any method outside of the class then we use public keyword. but we can use other keywords  also.
below I discuss the full use of this calss with return type discuss:


Class A
{
     int length;
     int width;

    public void Getdata(int x, int y) 

     {
           length= x;
           width= y;
      }
   public int Area()
     {
          int area= lenght * width ;
          return area;
     } 


}
Method Area()  is define and we calculate Area of Rectangle and put the result in area variable.


MEMBER ACCESS MODIFIERS:

 What to do if a class wants to hide its details from outsiders. In this context in OOP one term is used name: data hiding .
C# provides a set of access modifiers that can be used with the members of a class to control their visibility to outside users. 


MODIFIERS          

Private                                 
Public                           
Protected             
Internal                   
Public Internal      

All members are private access by default in C#. If we want to assign other visibility then we should specify suitable access modifier.

class Visibility-Test
{
        public int y;
        internal int z;
        protected double a;
        float b; // private default
 }

Methods and data fields that are declared public are directly accessible from an object instance. Private members cannot be accessed by an object instance but can be used directly by the methods inside the class.

HOW TO CREATE OBJECT:

Objects in C# create by using new operator.  The new operator creates an object of the specified class and return  a reference to that object.
here I am discussing previous declared class example:

A newA= new A() ;
we can define multiple object of the same class


A newA2= newA() ;
A newA3= new A () ;


CONSTRUCTORS:

Why we need Constructors: 

In a single line we can say constructors are required assign values to variables. We can do the say thing with the help of methods but its not the job methods, so constructors are come to the pictures. Constructors are valuable for other task also which we discuss later 
Constructors have the same name as the class itself and they do not specify a return type, not even void. This becuase they do not return any value.

Class A
{
     int length;
     int width;
    public A (int x, int y)  // Constructor  here
     {
           length= x;
           width= y;
      }
   public int RectArea()
     {
           int area= lenght * width ; // Area of Rectangle
           return area;
     } 
}
Constructor are usually declare as public but we can declare them as private or protected

Type of Constructor:

  1. Default Constructor
  2. Parameter Constructor
  3. Static Constructor
  4. Copy Constructor
Overloaded Constructors:
A class can contain more than one constructors, but all constructors have different- different parameters. This is called constructor overloading.

Static Constructor:
We can define a constructor as static also. A static constructor is called before any object of the class is created. It is usually used to assign initial values to static data members.

Class ABC
{
      static ABC ( )  // constructor
       {
                // initial static data values here
       }

}
Point to consider here that there is no access modifier on static constructors. It cannot take any, a class can have only one static constructors.

DESTRUCTORS:

Destructors is opposite to a constructor. It's amethod called when an object is no more required. The name of Desctuctor is same as class name and is preceded bu a tilde (~) sign. Like an constructor, destructor has no return type.

Class ABC
{
      ~ ABC ( )  // destructor
       {
          .....
       }
}

* destructor takes no parameters

Valuable Tips are:

  1. Static Variables are assigned when the class is loaded.
  2. Instance variables are assigned when an instance of the class created.
  3. This keyword which is a reference to the object that called the method.
  4. C# also permits to declaration of data field of a class as constants. This can be done by using const  keyword.
  5. The const members are implicitly static.
  6.  Indexers are location indicators and are used to access class objects.


Manipulating Strings

String manipulation is the most common part of the any programming language. Strings represent a sequence of characters. The easiest way to represent a sequence of characters in C# is by using a character array.
For example: 

                                           char [] charArray= new char[4];
                                           charArray [0]  =   'M';
                                           charArray [1]  =    'A';
                                           charArray [2]  =    'N';
                                           charArray [3]  =    'U';

 C# supports two types of strings, namely, immutable strings and mutable strings . C# also supports a feature known as regular expression that can be used for complex string manipulations and pattern matching.

We can create immutable strings using string or String objects in a number of ways:
  • Using ToString() method
  • Reading from the keyboard
  • Concatenating two objects
  • Copying from one object to another
  • Assigning string literals

Verbatim String :

Strings can also be created using what are known as verbatim strings. This type of strings start with @ symbol. This symbol tells the compiler that the string should be used verbatim even if it includes escape characters.

string S1= @ "\ABc\CSharpt\string";

String Methods:

string objects are immutable , meaning that we cannot modify the characters contained in them. How ever, since the string is an alias for the predefined System.String class in the CLR, there are many build in operations available that work with strings. All operations produce a modified version of the string rather than modifying the string on which the method is called.

Few Method are as below:


  1. Compare( )
  2. CompareTo ( )
  3. ConCat ( )
  4. Copy ( )
  5. CopyTo ( )
  6. Remove ( )
  7. Replace ( )
  8. Split ( )
  9. Trim ( )
  10. Substring ( )

INSERTING STRINGS

String methods are called using the string object on which we want to work. 

using System;
class StringFirstMethod
{
        public static void Main ()
         {
                  string s1="Hello";
                  string s2= s1.Insert(3,'M');                      //   s2    =  HelMlo

                   string s3= s2.Insert(5,'A');                    // s3    =   HelMlAo 
         }
}


COMPARING STRINGS

String class supports overload methods and operators to compare whether two strings are equal or not.
  • Overloaded Compare () method
  • Overloaded Equals () method
  • Overloaded == operator

COMPARE METHOD:


Compare method is further divided in two part.

(01)  First one take two string as parameters and compare them


int A= string.compare(s1,s2); 

This is case sensitive comparison and return different-different integer values which based the conditions.

  • if s1 equal to s2 then return Zero (0) integer
  • if s1 greater then s2 then return (1) positive integer
  • if s1 smaller then s2 then return (-1) negative integer

 Example:  if we have s1="abc" and s2="ABC", then we call the string.compare() method and store the value in integer variable

                int A= string.compare(s1,s2);

 This return -1, because smaller letter has a smaller ASCII value than uppercase letters.

 (02)  The second compare takes an additional bool type parameter to decide whether case should be ignored or not. If the bool parameter is true, case is igonored.

In this case equation is :

              int A= string.compare(s1,s2,true);

 This return 0, because we already pass true bool type parameter, hence it ignored the case. 
               
             abc = ABC
 


Equals Method
:

Here also we have two type of Equals method for comparing the strings.

           bool b1 = s2.Equals (s1);

           bool b2 = string.Equals (s2, s1);

These methods returns true if s1 and s2 are equal otherwise return false.

== Operator

We can say this is the traditional way of comparing two strings.

    bool b1= (s1 == s2) ;  
   returns true if both are equal otherwise false
 we can use this with if clause  also;

 if (s1==s2)
 {
   // conditional statement here
 }
 

Methods in C Sharp

In OOP Language, Objects are used as building  blocks in developing a program. They are run-time entities . They may present a person , a place or table of data.. etc.

Objects encapsulate data, and code to manipulate that data. The code designed to work on the data is know as methods in C# .

C# is pure object oriented language and therefore, every method must be contained within a class. 

DECLARING METHODS

 modifier type method-name (formal- parameter- list)
{
         method body 
}

Method declaration has five parts:
  • Name of the method
  • Type of value the  method returs (type)
  • List of parameter ( formal parameter list)
  •  Body of the method
  • Method modifiers (modifier)

THE MAIN METHOD:

C#  start execution at a method named Main( ). This method must be the static method of a class and must have either int or void as return type

                  public static int Main() 
                             or
                  public static void Main () 

The modifier public is used as the method must be called from outside the program. The Main  can also have parameters which may receive values from the command line at the time of execution.
                public static int Main (string [] args )
                           or
               public static void Main (string [] args)


INVOKING METHODS:



Once method have been define, they must be activated for operations. The process of activating a method is know as invoking or calling. The invoking is done using dot operator as below

            objectname.methodname (parameter);

Defining and invoking  method

using system;
Class FirstMethod 
{
      //define method
      int Cube( int x)
           {
                        return (x*x*x);
            }
}

Class MethodTest
{
  
      public static void Main()
       {
            //create the object of the class
              Method M = new Method();
            
          //Invoke the cube method
            int y= M.Cube(10);

          Console.Writeline ( y) ;
      
       }

}

Output: 1000

Calling a Static Method:


using system;
Class StaticMethod
{
       public static void Main()
       {
               double y = Square(2);    //calling method
                Console.Writeline(y); 

       }

       static int Square(int x) //Method definition 
       {
                   return (x * x);
         }
}

NESTING OF METHODS:

A Method can be called using only its name by another method of the same class. This is known asnesting of methods.

using system;

class Nesting
{
void Largest ( int m, int n)
           {
                int large=Max (m, n)                 // Nesting Method
                 console.writeline(large);
           }

           int Max( int a , int b)
         {
              int x=(a >b) ? a : b;
               return (x);
         }
}

class NestTesting
{
            public static void Main()
            {
                 Nesting next= new Nesting();
                 next.large(90, 75);                     // Method Call
             }
}

METHOD PARAMETERS

A method invocation creates a copy, specific to that invocation, of the formal parameters and local variables of that method. The actual argument list of the invocation assign values or variables references to the newly created formal parameters. within the body of a method, formal parameters can be used like any other variables.

The invocation involves not only passing the values into the method but also getting back the results from the method. For managing the purpose of passing values and getting back the results, C# have four kinds of parameters.


  1. Value parameters
  2. Reference parameters
  3. Output parameters
  4. Parameter arrays

Value parameters:

By default,  method parameters are passed by value. That is, a parameter declared with no modifier is passed by value and is called a value parameter. When a method is invoked, the values of actual parameters are assigned to the corresponding formal parameters. The values of the value parameters cab be changed within the method. The value of the actual parameter that is passed by value to a  method is not changed by any changes made to the corresponding formal parameter within the body of the method. This is because the methods refer to only copies of those variables when they are passed by value.

  using System;
 Class PassByValue
{
    static void Change (int n)
    {

             n= n+100;  //   value of n is changed here

     }

   public static void Main()
   {
         int  x=10;
          
        Change(x);
       
        Console.Writeline("value of x is:" + x);
  
   }

}

The value of x will produce the output is :  10

When method Change() in invoked, the value of x is assigned to n and a new location for n is created in the memory. Therefore, any change in n does not affect the value stored in the location of x

Reference parameters:

We can, however, force the value parameters to be passed by reference. To do this, we use he ref keyword. A parameter declared with the ref modifier parameter. 
                                
                               void Modify ( ref int y)

Unlike the value parameter, a reference parameter does not create a new storage location. Instead, it represents the same storage location as the actual parameter used in the method invocation.  Imporant point to consider here that: when we declare variable in reference type then make it sure that  corresponding argument in the method invocation must also be declared as ref .

OUTPUT PARAMETERS

Output parameter are used to pass results back to the calling method. This is achieved by declaring the parameters with an out keyword. Similar to a reference parameter, an output parameter does not create a new storage location. Instead, it becomes an alias to the parameter in the calling method. When a formal parameter is declared as out, the corresponding actual paramete in the calling method must also be declared as out.

using System;
class Output
{
   static void Sqaure ( int x, out int y )
  {
            y= x * x;

   }

   public static void Main ()
   {
         int m; // no need to initialized
        Sqaure ( 10, out m);
         Console.WriteLine("m=" + m);

   }

}

WHAT IS METHOD OVERLOADING:

C# allows us to create more than one method with the same name, but with the different parameter lists and different definitions. This is called method overloading. Method overloading is used when methods are required to perform similar tasks but using different input parameters.

Overloaded methods must differ in  number and or type of parameters they take. This enables the compiler to decide which one of the definitions to execute depending on the type and number of arguments in the method call. Note hat the  method's return type does not play any role in the overload resolution.

// Method definition

int Add ( int a, int b) {..... }

int Add ( int a , int b, int c) { ....}

double Add ( float x, float y} { ....}

double Add ( int x, float y) { ...} 

//Method calling

int m = Add ( 10,23) ;

int m =  Add (10,23,34) ;

double x = Add (1.0 F, 3.0 F) ;

The method selection involves the following steps:

  1. The compiler tries to find an exact match in which the types of actual parameters are the same and uses that method.
  2. If the exact match is not found, then the compiler tries to use the implicit conversions to the actual arguments and then uses the method whose match is unique. If the conversion creates multiple matches, then the compiler will generate an error message

Understanding of .Net Framework

Microsoft .Net platform includes the following components that would help develop a new generation of smart Internet services:

  • .NET infrastructure and Tools
  • .NET user experience
  • .NET building block
  • .NET device software
Origin .NET:
Before going to discuss about .Net we should discuss about origin of .Net and its features. 
  • OLE technology
  • COM technology
  • .NET technology
OLE Technology:
OLE(Object Linking and Embedding) technology developed by Microsoft in the early of 90s to enable easy interprocess communications. OLE provided support to archieve the following

  • To embed documents from one application into another application
  • To enable one application to manipulate objects located in another application
This enabled users to develop applications which required inter-operatbility between various products such as MS Word and MS Excel

COM Technology:
At first of COM technology, the monolithic approach had been used for developing software. But when programs become too large and complex the monolithic approach leads to a number of problems in terms of maintainability and testing of software. To over come with the problem Microsoft come up with component based model for development software. In this approach software broken up in number of modules( independent components) where each one offers a particular service. Each component can tested and developed independently and then integrate with main system. This technique is called Component Object Model (COM)  and the software built using COM is referred to as componentware.
it provides great flexibility to developers:
  • reduce overall complexity of the software
  • enable distributed development across multiple organizations or departments
  • enhance software maintainability
.NET Technology:

.NET technology is a third generation component model. This provides a new level of inter-operability compared to COM technology. COM provides a standard binary mechanism for inter module communication. This mechanism is replaced by an intermediate language called Microsoft Intermediate Language (MSIL) or IL.  Various .NET compilers enforce inter operability by complying code  into IL, which automatically compatible with other IL modules. An inherent characteristic of IL code is metadata. Metadata is data about the data and describes its characteristic, including data types and locations. IL allows for true cross language integration. in addition to IL,.NET includes a host of other technologies and tools that will enable us develop and implement Web based applications easily.

THE .NET FRAMEWORK
In short .Net framework provides an environment for building, developing and running web services and other applications. It consists of three distinct technology:-

  1. Common Language Runtime (CLR)
  2. Framework Based Classes
  3. User interface program (Asp.net and Win forms) 
  CLR:
We can say CLR is heart and soul of the .Net framework. As the name its comes, CLR provides run time environment in which programe written in C# and other .Net languages are executed.  It also supports cross language interoperability.
CLR supports number of services as follows:

  1. Loading and execution of the program
  2. Memory isolation for application
  3. Verification of type safety
  4. Compilation of IL into native executable code
  5. Providing metadata
  6. Memory management (automatic garbage collection)
  7. Enforcement of security
  8. Managing errors and exceptions
  9. Support for tasks such as debugging and profiling
  10. Interoperability with other systems
Common Type System (CTS):
The .Net framework provides multiple language support using the features known as Common Type System that build into the CLR. The CTS supports a variety of types and operations found in most programming languages and therefore calling one language from another does not require type conversions. we can build .Net program in a number of other languages including C++ and Visual Baisc .

Common Language Specification (CLS):
The CLS specification defines a set of rules that enables interoperability on the .Net platform. These rules guide the third party compiler designers and library buuilders. The CLS is a subset of CTS and therefore the language supporting the CLS can use each others class libraries as if they are their own.

Microsoft Intermediate Language (MSIL):
MSIL simply called IL, is an instruction set into which all the .NET programs are compiled.  it is akin to assembly language and contains instructions for loading, storing, initializing and calling methods.  When we compile a C# program or any program written in a CLS compliant language, the code is compiled into MSIL.

Managed Code: 
CLR is responsible for managing the execution of code compiled for the .Net platform. The code that satisfies the CLR runtime in order to execute is referred to as managed code.  Compiler that are compatible to the .Net platform generate managed code. The managed code generated by C# is IL code. 


stats counter
your visitor number