Tuesday 14 October 2014

C# Strings

C# strings
In C#, a string is an object of type string and the value of that string is text.We can use C#
strings as array of characters but more common and preferable practice is to declare a string variable for using strings. C# treats the strings as objects that encapsulate all the manipulation, sorting, and searching methods normally applied to strings of characters. Each string in C# is immutable sequence of Unicode characters. In simple words, we can say that the methods in C# to change or modify the string actually does not change the string but they only return a modified copy of that C# string and the original string remains intact.

Creating a String in C#

In C# strings most common way to create string is to assign quoted strings of characters which is knows as string literal, to a user-defined variable with string type.
string overString =  "This is a string literal";
Our string is between the double quotes. In the same way quoted strings can include escape characters like "/n" or "/t" and i hope you have knowledge of escape characters.
We can also create string objects in more ways from the above one :

  • Using a string class constructor.
  • Using the string concatenation operator(+).
  • Retrieving a property or calling a method that will return a string.
  • Calling any formatting method to convert a value or object to its storing representation.



using System;
namespace StringApp
{
    class Program
    {
        static void Main(string[] args)
        {
           //Through the string literal and string concatenation
            string firstName, lastName;
            firstName = "Paul";
            lastName = "Walker";
            string fullName = firstName + lastName;
            Console.WriteLine("Full Name: {0}", fullName);
            //Using string constructor
            char[] sLetters = { 'H', 'e', 'l', 'l','o' };
            string greetings = new string(sLetters);
            Console.WriteLine("Greetings: {0}", greetings);
            //Methods returning string
            string[] sArray = { "Hello", "From", "Tutorials", "Point" };
            string meSSage = String.Join(" ", sArray);
            Console.WriteLine("Message: {0}", meSSage);
            //Formatting method to convert a value
            DateTime waiting = new DateTime(2014, 10, 10, 17, 58, 1);
            string chat = String.Format("Message sent at {0:t} on {0:D}",
            waiting);
            Console.WriteLine("Message: {0}", chat);
            Console.ReadKey() ;
        }
    }
}

C# strings has various properties and methods for working with string objects and we will work on these further.

Sunday 12 October 2014

All about abstract classes.with examples in C#

 If you watch the dictionary for the word "Abstract" then it will given there that thought or idea having no physical existence and just conceptual. So we have to built this idea with physical existence. MSDN library tells that the "abstract" keyword  shows that the thing has a missing or incomplete implementation or method and must be completed by others.

An abstract method has no implementation. It creates a method name and signature that must be implemented in all derived classes. Abstract classes establish a base for derived classes, but it is not legal to instantiate an object of an abstract class. Once you declare a method to be abstract, you prohibit the creation of any instances of that class.

The abstract keyword can be used with the classes, properties, methods, events, indexers. When we use the keyword "abstract" with the class, then it indicates that the class is intended to be a base class (no physical existence)  and can have abstract methods that will must be implemented in derived classes (physical existence).

Abstract Class has special kind of Class with no implementation. And it also cannot be instantiated. All of the functionality and the implementation is provided by its derived classes. Abstract class can have both abstract methods and non-abstract methods. It is not compulsory that only abstract methods are in the abstract class. We can also have abstract class with non-abstract members in it.

Why we uses abstract classes?


By using of abstract classes we can provide some default functionality for all derived classes of base class, to extend from. This helps us in code duplication.

Now suppose we have an iPhone class and then creating two subclasses iPhone 4 and iPhone 4S, means they are inherited with iPhone class. Practically we don't want an object of iPhone but we want to know about the model of iPhone. So it means that iPhone class is abstract class with no physical existence while iPhone 4 and iPhone 4S are derived class with physical existence. As i previously told that abstract class has some basic functionality for the derived classes so for our abstract clas that is iPhone class we can add some predefined functions or methods like Call(), SMS() so all the subclasses or iPhone models can share these methods. We can also add abstract methods like Color(), Model() in the base class (iPhone class) and it is necessary to implement these methods in the classes derived by base class(iPhone class). So we have main advantage of this approach is that when new class will be inherited by iPhone class then we does not have to define the Call() & SMS() functions again because they are already defined in the base class. We just have to implement them in base class only one time and we have done. So by the help of abstract class we have some default functionality for all our derived classes and also help us to avoid the code duplication.

How to define Abstract Classes.


As defined above that abstract is a keyword so we just have to add this keyword before the class definition. Watch the example below, we just use abstract keyword with a class iPhone.

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

namespace AbstractClassDemo
{
    abstract class iPhone               //Definition for abstract class
    {

    }
    class Program
    {
        
        static void Main(string[] args)
        {
        }
    }
}

Note: We cannot create an object/instance of the abstract class otherwise we will get error by the compiler.

One more very important thing that abstract methods, properties, events and indexers that we defined in abstract class should be kept as public. If we set them private or not set them public then compiler will generate error.

Now we will add members and methods in the base class so derived classes can use that directly. As previously described that we can have abstract and non-abstract methods in the abstract class. Here is the example of abstract class with non-abstract members in it.


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

namespace AbstractClassDemo
{
    abstract class iPhone               //Definition for abstract class
    {
        //Here is our non-abstract method
        void Call()          //all methods are public by default
        {
            Console.WriteLine("This is Call Method in base class.");
        }

    }

    class Program
    {
        
        static void Main(string[] args)
        {
        }
    }
}


Our base class that is iPhone Class has a non-abstract method Call() that provides the default functionality to all sub classes that are derived from it.We cannot create and object of iPhone class but we can use the Call() method in the derived classes.


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

namespace AbstractClassDemo
{
    abstract class iPhone               //Defenition for abstract class
    {
        //Here is our non-abstract method
      public void Call()          //all methods are public by default
        {
            Console.WriteLine("This is Call Method in base class.");
        }
    }

    class Program : iPhone
    {

        static void Main(string[] args)
        {
            //Instance created for derived class 
            Program program = new Program();
            program.Call();
            Console.ReadKey();  
        }
    }
}

Abstract Class in C#








In the above code you can watch simple inheritance of an abstract class into a derived or concrete class. This type of inheritance can also be done by creating two concrete classes. But why we choose to create abstract class?

So the answer is, as previously described to provide default functionality to derived classes and add abstract methods. The iPhone class is inherited by all the iPhone models, so it is simple that Call() method is required in all models. So instead of creating the call function separately in each class we just define a Call() method in our abstract class so that each derived class automatically have the Call() method and there is no need to define it again.

Each iPhone model has some of its own unique features like color, model etc. So we define a contract in the abstract class for abstract methods that should must be implemented in derived classes as mentioned above that it is necessary to implement all of the abstract methods. These types of contracts are called abstract methods. In the example below the Model() is the abstract method. Again note that abstract methods have only signatures and have no implementation. And all the sub classes must have to implement them.

Like abstract classes , abstract methods are also declared using the abstract keyword . Abstract method should must be set public because it cannot be private otherwise compiler will generate error.

Now we will add abstract method in our base class. One thing to remember again that abstract members should be set as public so all the derived classes can access them.

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

namespace AbstractClassDemo
{
    abstract class iPhone               //Defenition for abstract class
    {
        //Here is our non-abstract method
      public void Call()          //all methods are public by default
        {
            Console.WriteLine("This is Call Method in base class.");
        }

      //Abstract Method kept as Public   
      public abstract void Model();  
    }

    class Program : iPhone
    {

        static void Main(string[] args)
        {
            //Instance created for derived class 
            Program program = new Program();
            program.Call();
            Console.ReadKey();  
        }
    }
}

The Model() is abstract method and in C# abstract method enforces all derived classes to implement it. So now we will define new concrete class iPhone6 that will that inherits the methods of abstract class iPhone and implement the abstract methods. If we does't implement the methods then compiler will generate method for use because it is compulsory to implement the abstract methods.

In the derived class we will implement the abstract methods by overriding them. We will use override keyword for that purpose in the implementation of method in derived class.

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

namespace AbstractClassDemo
{
    abstract class iPhone               //Defenition for abstract class
    {
        //Here is our non-abstract method
      public void Call()          //all methods are public by default
        {
            Console.WriteLine("This is Call Method in base class.");
        }

      //Abstract Method kept as Public   
      public abstract void Model();  
    }

    class iPhone6 : iPhone
    {
        //Abstract Method Implementation   
        public override void Model()
        {
            Console.WriteLine("Model: The model of this iPhone is iPhone6");
        }
        public void LaunchDate()
        {
            Console.WriteLine("Launch Date: This iPhone was launched in 2014");
        }  
    } 
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}


So by using override keyword you can override the abstract methods of abstract class. But if your method in derived class is not related to the method of base class then use the new keyword. So compiler will understand that the method of derived class has nothing to do with the method of base class.


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

namespace AbstractClassDemo
{
    abstract class iPhone               //Defenition for abstract class
    {
        //Here is our non-abstract method
      public void Call()          //all methods are public by default
        {
            Console.WriteLine("This is Call Method in base class.");
        }

      //Abstract Method kept as Public   
      public abstract void Model();  
    }

    class iPhone6 : iPhone
    {
        //Abstract Method Implementation   
        public override void Model()
        {
            Console.WriteLine("Model: The model of this iPhone is iPhone6");
        }
        public void LaunchDate()
        {
            Console.WriteLine("Launch Date: This iPhone was launched in 2014");
        }  
    } 
    class Program
    {
        static void Main(string[] args)
        {
            iPhone6 iphone6 = new iPhone6();
            iphone6.Call();
            iphone6.Model();
            iphone6.LaunchDate();
            Console.ReadKey();
            Console.ReadKey();  
        }
    }
}

Abstract Class in C# With Example


Hope this article will help you to understand Abstrac Class and its implementation.