Showing posts with label OOPS. Show all posts
Showing posts with label OOPS. Show all posts

Wednesday, 13 April 2016

Feature and Property of Extension Methods


The following list contains basic features and properties of extension methods:
  1. It is a static method.
  2. It must be located in a static class.
  3. It uses the "this" keyword as the first parameter with a type in .NET and this method will be called by a given type instance on the client side.
  4. It also shown by VS intellisense. When we press the dot (.) after a type instance, then it comes in VS intellisense.
  5. An extension method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement.
  6. You can give any name for the class that has an extension method but the class should be static.
  7. If you want to add new methods to a type and you don't have the source code for it, then the solution is to use and implement extension methods of that type.
  8. If you create extension methods that have the same signature methods as the type you are extending, then the extension methods will never be called.
Example:
We create an extension method for a string type so string will be specified as a parameter for this extension method and that method will be called by a string instance using the dot operator.

public static int WordCount(this string str)
  {
     string[] strArray = str.Split(new char[] { ' ', '.', '?' }, 
                              StringSplitOptions.RemoveEmptyEntries);
     int wordCount = strArray.Length;
     return wordCount;
  }
In the above method WordCount(), we are passing a string type with this so it will be called by the stringtype variable, in other words a string instance.
Now we create a static class and two static methods, one for the total word count in a string and another for the total number of characters in a string without a space.
using System;
namespace ExtensionMethodsExample
{
   public static class Extension
    {
       public static int WordCount(this string str)
       {
           string[] userString = str.Split(new char[] { ' ', '.', '?' },
                                       StringSplitOptions.RemoveEmptyEntries);
           int wordCount = userString.Length;
           return wordCount;
       } 
       public static int TotalCharWithoutSpace(this string str)
       {
           int totalCharWithoutSpace = 0;
           string[] userString = str.Split(' ');
           foreach (string stringValue in userString)
           {
               totalCharWithoutSpace += stringValue.Length;
           }
           return totalCharWithoutSpace;
       }
    }
} 

Now we create an executable program that has a string as an input and uses an extension method to count the total words in that string and the total number of characters in that string then show the result in a console screen.
using System;
namespace ExtensionMethodsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string userSentance = string.Empty;
            int totalWords = 0;
            int totalCharWithoutSpace = 0;
            Console.WriteLine("Enter the your sentance");
            userSentance = Console.ReadLine();
            //calling Extension Method WordCount
            totalWords = userSentance.WordCount();
            Console.WriteLine("Total number of words is :"+ totalWords);
            //calling Extension Method to count character
            totalCharWithoutSpace = userSentance.TotalCharWithoutSpace();
            Console.WriteLine("Total number of character is :"+totalCharWithoutSpace);
            Console.ReadKey();
        }
    }
} 
Output-



Tuesday, 12 April 2016

What are access modifiers in C#?


Access modifiers determine the scope of the method or variables that can be accessed from other various objects or classes. There are 5 types of access modifiers, and they are as follows:-
  • Public. 
  • Private. 
  • Protected. 
  • Internal 
  • Protected Internal 
Public: The class member, that is defined as public can be accessed by other class member that is initialized outside the class. A public member can be accessed from anywhere even outside the namespace.

Example:-

using System;
namespace Public_Access_Specifiers
{
    class access
    {
        // String Variable declared as public
        public string name;

        // Public method
        public void print()
        {
            Console.WriteLine("\nMy name is " + name);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            access ac = new access();
            Console.Write("Enter your name:\t");

            // Accepting value in public variable that is outside the class
            ac.name = Console.ReadLine();
            ac.print();
            Console.ReadLine();
        }
    }
}

Output:



Private: The private access specifiers restrict the member variable or function to be called outside from the parent class. A private function or variable cannot be called outside from the same class. It hides its member variable and method from other class and methods. However, you can store or retrieve value from private access modifiers using get set property. You will learn more about get set property in lateral chapter.

Example:

using System;
namespace Private_Access_Specifiers
{
    class access
    {
        // String Variable declared as private
        private string name;

        public void print() // public method
        {
            Console.WriteLine("\nMy name is " + name);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            access ac = new access();
            Console.Write("Enter your name:\t");

            // raise error because of its protection level
            ac.name = Console.ReadLine();

            ac.print();
            Console.ReadLine();
        }
    }
}


Output:

Error 1: Private_Access_Specifiers.access.name' is inaccessible due to its protection level

In the above example, you cannot call name variable outside the class because it is declared as private.

Protected: The protected access specifier hides its member variables and functions from other classes and objects. This type of variable or function can only be accessed in child class. It becomes very important while implementing inheritance.

Example:


using System;
namespace Protected_Specifier
{
    class access
    {
        // String Variable declared as protected
        protected string name;
        public void print()
        {
            Console.WriteLine("\nMy name is " + name);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            access ac = new access();
            Console.Write("Enter your name:\t");
            // raise error because of its protection level
            ac.name = Console.ReadLine();
            ac.print();
            Console.ReadLine();
        }
    }
}

Output: 
'Protected_Specifier.access.name' is inaccessible due to its protection level.

This is because; the protected member can only be accessed within its child class. You can use protected access specifiers as follow:

Example:

using System;
namespace Protected_Specifier
{
    class access
    {
        // String Variable declared as protected
        protected string name;
        public void print()
        {
            Console.WriteLine("\nMy name is " + name);
        }
    }

    class Program : access // Inherit access class
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            Console.Write("Enter your name: ");
            p.name = Console.ReadLine(); // No Error!!
            p.print();
            Console.ReadLine();
        }
    }
}

Output:



Internal: The internal access specifier hides its member variables and methods from other classes and objects, that is resides in other namespace. The variable or classes that are declared with internal can be access by any member within application. It is the default access specifiers for a class in C# programming.

Example:

using System;
namespace Internal_Access_Specifier
{
    class access
    {
        // String Variable declared as internal
        internal string name;
        public void print()
        {
            Console.WriteLine("\nMy name is " + name);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            access ac = new access();
            Console.Write("Enter your name:\t");
            // Accepting value in internal variable
            ac.name = Console.ReadLine();
            ac.print();
            Console.ReadLine();
        }
    }
}

Output :



Protected Internal: The protected internal access specifier allows its members to be accessed in derived class, containing class or classes within same application. However, this access specifier rarely used in C# programming but it becomes important while implementing inheritance.

Example:

using System;
namespace Protected_Internal
{
    class access
    {
        // String Variable declared as protected internal
        protected internal string name;
        public void print()
        {
            Console.WriteLine("\nMy name is " + name);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            access ac = new access();
            Console.Write("Enter your name:\t");
            // Accepting value in protected internal variable
            ac.name = Console.ReadLine();
            ac.print();
            Console.ReadLine();
        }
    }
}


Variables in C#



A variable refers to the memory address. When you create variable, it holds space in the memory that is used for storing temporary data. As you know c# data types has predefined size. Here we will try to understand how to use data types to create variable.

using System;

namespace Variable
{
  class Program
   {
     static void Main(string[] args)
      {
        //cretaing integer type variable
        int num1, num2, result;
        //Displaying message
        Console.WriteLine("Please enter first value");
          
        //Accepting Value in num1
        num1 = Int32.Parse(Console.ReadLine());
        //Displaying message
        Console.WriteLine("Enter second Value");
        //Accepting Value
        num2 = Int32.Parse(Console.ReadLine());

        result = num1 + num2; //processing value

        Console.WriteLine("Add of {0} and {1} is {2}", num1, num2, result); //Output

        Console.ReadLine();
      }
   }
}

Output 



In the preceding example we create three integer type variable num1, num2 and result. num1 and num2 is used for accepting user value and result is used for adding both number. The new thing in the preceding example is number of placeholders.

 Console.WriteLine("Add of {0} and {1} is {2}", num1, num2, result);
If you want to display more than one variable values then you will have to assign place holder for each variables. In the preceding line {0} denotes to num1, {1} denotes to num2 and {2} denotes to result.

Conversion

C# accepts string value by default. If you are using other value then you will have to convert of specific data types.

num1 = Int32.Parse(Console.ReadLine());

You can use the following method to convert one data type to another data type.

 
 Integer = int32.parse() or Convert.ToInt32()
 Float = (float)
 Double=Convert.ToDouble()
 Decimal=Convert.ToDecimal()
 Byte=Convert.ToByte()


Features of Static Class


C# provides the important feature to create static classes, there are two main features of a static class:-
  1. No object of static class can be created
  2. A static class must contain only static members. 
Then it is important that what is the main benefit to create a static class, the main benefit of making static class is we do not need to make any instance of this class, all members can be accessible with its own name.

Declaration:

A static class is created by using keyword 'Static' as shown here:

Static class Clasname
{
   //C#
}

One more thing that must be noted in static class, all members must be explicitly specified as static, static class does not automatically make its members static. Static class can contain a collection of static methods.

Example:

using System;
static class Shape
{
    public static double GetArea(double height, double width)
    {
        return height * width;
    }
}
class Ractangle
{
    private void GetRactangleArea()
    {
        Double area;
        area = Shape.GetArea(10, 5);
    }
}

Here 'Shape' is static class, it contain static function GetArea. Rectangle is other class and with in GetArea function can be access without creating instance of Class Shape.

Although a static class cannot have an instance constructor, it can have a static constructor.

If a class is declared as static then the variables and methods must be declared as static.

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

The main features of a static class are:-

  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors or simply constructors as we know that they are associated with objects and operates on data when an object is created.
Example

static class Registration
{
  //All static member variables
   static int nCollegeId; //College Id will be same for all the students studying
   static string sCollegeName; //Name will be same
   static string sColegeAddress; //Address of the college will also same

    //Member functions
   public static int GetCollegeId()
   {
     nCollegeId = 100;
     return (nCollegeID);
   }
    //similarly implementation of others also.
} //class end

public class student
{
    int nRollNo;
    string sName;

    public GetRollNo()
    {
       nRollNo += 1;
       return (nRollNo);
    }
    //similarly ....
   public static void Main()
   {
     //Not required.
     //Registration objReg= new Registration();

     //.
     int cid= Registration.GetCollegeId();
     string sname= Registration.GetCollegeName();

   } //Main end
}

Monday, 11 April 2016

Data Types in C#


C# is a strongly typed language. It means, that you cannot use variable without data types. Data types tell the compiler that which type of data is used for processing. Such as if you want to work with string value then you will have to assign string type variable to work with. C# provides two types of data types: Value types and Reference types.
Value type data type stores copy of the value whereas the Reference type data types stores the address of the value. C sharp provides great range of predefined data types but it also gives the way to create user defined data types.
A complete detail of C# data types are mentioned below:

Value Types:


Data TypesSizeValues
sbyte8 bit-128 to 127
byte8 bit0 to 255
short16 bit-32,768 to 32,767
ushort16 bit0 to 65,535
int32 bit-2,147,483,648 to 2,147,483,647
uint32 bit0 to 4,294,967,295
long64 bit-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulong64 bit0 to 18,446,744,073,709,551,615
char16 bit0 to 65535
float32 bit-1.5 x 1045 to 3.4 x 1038
double64 bit-5 x 10324 to 1.7 x 10308
decimal128 bit-1028 to 7.9 x 1028
bool---True or false

Reference Types:


Data TypesSizeValues
stringVariable length0-2 billion Unicode characters
object------


Wednesday, 6 April 2016

What are queues and stacks?

Stacks-

Stacks refer to a list in which all items are accessed and processed on the Last-In-First-Out (LIFO) basis. In a stack, elements are inserted (push operation) and deleted (pop operation) from the same end called top.

Queues-

Queues refer to a list in which insertion and deletion of an item is done on the First-In- First-Out (FIFO) basis. The items in a queue are inserted from the one end, called the rear end, and are deleted from the other end, called the front end of the queue.


Differentiate between an abstract class and an interface.

Abstract Class:

  • A class can extend only one abstract class
  • The members of abstract class can be private as well as protected.
  • Abstract classes should have subclasses
  • Any class can extend an abstract class.
  • Methods in abstract class can be abstract as well as concrete.
  • There can be a constructor for abstract class.
  • The class extending the abstract class may or may not implement any of its method.
  • An abstract class can implement methods.

Interface:

  • A class can implement several interfaces
  • An interface can only have public members.
  • Interfaces must have implementations by classes
  • Only an interface can extend another interface.
  • All methods in an interface should be abstract
  • Interface does not have constructor.
  • All methods of interface need to be implemented by a class implementing that interface.
  • Interfaces cannot contain body of any of its method.

Featured post

What is SharePoint?

Microsoft SharePoint is an extensible platform that provides a range of products that can help organizations with solution for a variety...