Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

How to Create a Basic Crystal Report using Windows Forms and C#

From this post, I will show you how to create a basic Crystal Report. You don't need to have previous knowledge in reporting. Just a little bit knowledge in C# and SQL would be enough.

In SQL Server, I'm creating a database named 'Company' and inside that I have a table named 'Employee'. An employee has an id, a name and a designation. Sample values are added into the Employee table.

Then in Microsoft Visual Studio, I'm creating a Windows Forms Application.

Then I need to add a data source to the project. Right click on the project in Solution Explorer. Select Add and Click on New Item.
Then in the dialog box, select 'Data' as the Category and from Template, select DataSet. The name for the new data set is given as EmployeeDataSet.xsd in this example. Then click Add.
Then the EmployeeDataSet.xsd file will be opened. If not open it from the Solution Explorer. In the Toolbox, under DataSet, click on the TableAdapter, drag it to the working area and drop it.
Then the Table Adapter Configuration Wizard will be opened.
Click on New Connection. Then give the database details appropriately. In this example, server name is localhost and the database is Company. Then test the connection.
Once the connection is successful, click OK.
Now the connection string is created. Click next in the Table Adapter Configuration Wizard.
In the next window, you can give a name for the connection string. For my convenience, I'll leave the default name. Then click Next.

In the next window, select 'Use SQL Statements' and click Next.
In the next window, you can specify the SQL query for the table adapter. I'll use the Query Builder to build the query.
In the Add Table window, select the tables you want for the query and click on Add. Then close the window. In this example I'm adding the Employee table.
\
Then select the columns needed for the query and click Execute Query to view the result. Then click OK.

Now the query is successfully built. Click Next.

Make the selections as shown in the following image and click Next.
 Now the table adapter is successfully configured. Click Finish.

Now you can see the configured table adapter in the working area.

Now we need to add a Crystal Report to the project. Right click on the project in the Solution Explorer and  select Add -> New Item. From the categories, select Reporting and from the Templates, select Crystal Report. The name given for the report in this example is EmployeeReport.rpt . Then click Add.
 Here I'm creating a Standard Report using the Reporting Wizard.
In the wizard, select the data table that you want in the report. Here I'm selecting the Employee table. Then click Next.
Then select the fields to be displayed in the report and click Next.

Next thing is Grouping. Here I don't want to group the displaying fields. So I'll click Next without making any selection.
Next thing is filtering fields. Here I don't need any filtering so I'll click Next.
Next thing is selecting a style for the report. I'll select Standard style and click Finish.
Now the report is created. You can drag the fields and customize the appearance. Add lines and images if you need. I'll just leave it as it is.
Now the designing is over. Now we need to view the report. Get the Windows Form (here Form1). In Tool box, under Reporting menu, click on the Crystal Report Viewer and drag it to the form and drop. 


Now we need to write little bit coding to display data on the report viewer. Go to the Form Load event and write the following code.
Now run the project and see the output report.

Feel free to put your comments here !

“Some Best Practices for C#”

Use Proper Naming Conventions

You should prefer proper naming conventions for consistency of your code. It is very easy to maintain the code if consistent naming is used all over the solution. Here are some naming conventions which are generally followed by .NET developers:
  • Always use Camel case (A word with the first letter lowercase, and the first letter of each subsequent word-part capitalized) while declaring variables.
  • Use Pascal (A word with the first letter capitalized, and the first letter of each subsequent word-part capitalized) naming format while declaring Properties.
  • Avoid all uppercase or lowercase names for properties, variables or method names. Use all uppercase when declaring const variables.
  • Never use a name that begins with a numeric character.
  • Always prefer meaningful names for your class, property, method, etc. This will be very useful for you to maintain the code in future. For example, “P” will not give proper meaning for a class. You will find it difficult to know about the class. But if you use “Person”, you will easily understand by it.
  • Never build a different name varied by capitalization. It is a very bad practice. It will not be useful while developing code, as you will not know what is “person” class and what is “Person” class!!! But from the above scenario, it can be very easily understandable that “person” is an instance variable of “Person” class.
  • Don't use the same name used in .NET Framework. People who are new to your code have great difficulty to understand it easily.
  • Avoid adding prefixes or suffixes for your identifiers. Though in some guidelines, they use “m_” and in some other they use “_” as the prefix of variable declaration. I think it is not that much useful. But, it depends on your organizational coding practices. This point is contradictory based on various organizations and there is no strict guidance on it.
  • Always use “I” as prefix for Interfaces. This is a common practice for declaring interfaces.
  • Always add “Exception” as suffix for your custom exception class. It will give better visibility to your exception class.
  • Never prefix or suffix the class name to its property names. It will unnecessarily increase the property name. If “Firstname” is a property of “Person” class, you can easily identify it from that class directly. No need to write “PersonFirstname” or “FirstnameOfPerson”.
  • Prefix “Is”, “Has” or “Can” for boolean properties like “IsVisible”, “HasChildren”, “CanExecute”. These give proper meaning to the properties.
  • Don't add prefix for your controls, instead write proper name to identify the control.

Decide between Value Types and Reference Types

Whenever you need to create a type, first ask yourself a question “What you want and Why you want it?”. If you could answer your question, you can decide between the type you want to use. If you want to store your data, use value types and when you want to create an instance of your type by defining the behavior, use reference types. Value types are not Polymorphic whereas, the Reference types can be. Value types are most efficient in terms of memory utilization over reference types and produce less help fragmentation & garbage. If you want to pass values to a method implementation, decide what you want to do and based upon your requirement, decide between value types and reference types. Use of reference type variables actually change the original value but use of value type will create a copy of the original variable and pass across the method. Thus, it protects your original value from accidental changes. Let's see them in real example. In the below code, we are passing the variable “i” as value type and in the method implementation incrementing it by 10. As it was passed by value, you will see the original value “5” as output of the program code.
static void Main(string[] args)
{
 int i = 5;
 SetValues(i);

 System.Console.WriteLine("Currently i = " + i); // will print "Currently i = 5"
}

static void SetValues(int x)
{
 x += 10;
}
In the below code, as we are sending “i” as a reference, it will change the original value of “i” inside the method and hence you will see 15 as the output in the screen.
static void Main(string[] args)
{
 int i = 5;
 SetValues(ref i);

 System.Console.WriteLine("Currently i = " + i); // will print "Currently i = 15"
}

static void SetValues(ref int x)
{
 x += 10;
}
Hence, decide before you start the implementation, else once implemented it will be very difficult to change them over your huge application.

Always Use Properties instead of Public Variables

Reason behind this is, it makes your code properly encapsulated in OOPs environment. By using getters & setters, you can restrict the user directly accessing the member variables. You can restrict setting the values explicitly thus making your data protected from accidental changes. Also, properties give you easier validation for your data. Let's see a small code:
public class Person
{
 public string name;

 public string GetNameInLowerCase()
 {
  return string.IsNullOrWhiteSpace(name) ? 
    string.Empty : name.ToLower();
 }

 public string GetNameInUpperCase()
 {
  return string.IsNullOrWhiteSpace(name) ? 
    string.Empty : name.ToUpper();
 }
}
In the above example, you will see you have to check every time for the Null value as somebody from outside can easily change the value accidentally and create a Bug in your code. If you don't want that Bug in your code, what you will do is, use the property implementation of the variable (making it private) and then access the property. This gives more reliability over your code. Let’s see an example:
public class Person
{
 public string name;

 public string Name
 {
  get
  {
   return string.IsNullOrWhiteSpace(name) ? string.Empty : name;
  }
  set { name = value; }
 }

 public string GetNameInLowerCase()
 {
  return Name.ToLower();
 }

 public string GetNameInUpperCase()
 {
  return Name.ToUpper();
 }
}
Now in this case, you don't have to think about checking the value against Null every time. The getter implementation of the property will take care of it. So, once implementation but use in multiple places. So, if someone explicitly sets the “Name” property to null, your code will have no impact on it. This is just a sample code to discuss with you about the need of property instead of public member variable. Actual implementation may vary based on your requirement.
public class Person
{
 public string Name { get; private set; }
 public string Age { get; }
}
If you don't want anybody to set the Property explicitly from outside, you can just only implement the getter inside the property implementation or mark the setter as private. Also, you can implement the properties from any interface, thus gives you more OOPs environment.

Use Nullable Data Types Whenever Required

Sometimes, you may need to store null as the value of an integer, double or boolean variable. So how can you do this? The normal declaration doesn't allow you to store the null as value. C# now has the feature of nullable data types. Just a small change in your declaration. That’s it!!! You are good to go for storing null values. Only you have to use the “?” modifier. You have to place it just after the type. To define an integer, you would normally do the following declaration:
int index = 0; // simple declaration of int
To convert this as an nullable data type, you have to modify a bit to declare like this:
int? index = null; // nullable data type declaration
Once you add the “?” modifier to the data type, your variable will become nullable and you will be able to store “null” value to it. Generally it is helpful when used with the boolean values.

Prefer Runtime Constants over Compile time Constants

Runtime constants are always preferred than the Compile time constants. Here you may ask what is runtime constant and what is compile time constant. Runtime constants are those which are evaluated at the runtime and declared with the keyword “readonly”. On the other side, compile time constants are static, evaluated at the time of compilation and declared with the keyword “const”.

public readonly string CONFIG_FILE_NAME = "web.config"; // runtime constant
public const string CONFIG_FILE_NAME = "web.config"; // compile time constant
So, what is the need to prefer readonly over const variables? Compile time constants (const) must be initialized at the time of declaration and can’t be changed later. Also, they are limited to only numbers and strings. The IL replaces the const variable with the value of it over the whole code and thus it is a bit faster. Whereas, the Runtime constants (readonly) are initialized in the constructor and can be changed at different initialization time. The IL references the readonly variable and not the original value. So, when you have some critical situation, use const to make the code run faster. When you need a reliable code, always prefer readonly variables.

Prefer “is” and “as” Operators While Casting

It is better to use “is” and “as” operator while casting. Instead of Explicit casting, use the Implicit casting. Let me describe to you with the example of a code.
// this line may throw Exception if it is unable to downcast from Person to Employee
var employee = (Employee) person;
In the above code, suppose your person is a Customer type and when you are converting it to Employee type, it will throw Exception and in that case, you have to handle it using try{} catch{} block. Let’s convert the same using “is” and “as” operators. See the below code:
// check if the person is Employee type
if(person is Employee)
{
 // convert person to Employee type
 employee = person as Employee;
}

// check if the person is Customer type
else if(person is Customer)
{
 // convert person to Customer type
 customer = person as Customer;
}
In the above code, you can see that, in the second line I am checking whether the person is a Employee type. If it is of type Employee, it will go into the block. Else if it is a Customer type, will go to the block at line 12. Now, convert it with the “as” operator, as shown in line 5. Here, if it is unable to convert, it will return as null but will not throw any exception. So, in the next line, you can check whether the converted value is null. Based on that, you can do what you want.

Prefer string.Format() or StringBuilder for String Concatenation

Any operation in the string will create a new object as string is a mutable object. If you want to concatenate multiple strings, it is always better to use string.Format() method or StringBuilder class for the concatenation.
string str = "a";
str += "h";
str += "s";
str += "a";
str += "n";
 
Console.WriteLine(str); 
In case of string.Format(), it will not create multiple objects instead will create a single one. StringBuilder as an immutable object will not create separate memory for each operation. So your application memory management will not be in critical stage. Hence, it is always preferable to do such operations either using string.Format() or StringBuilder.
The above code will create a new string object whenever we add a new string there. Using string.Format(), you can write the following code:
string str = string.Format("{0}{1}{2}{3}{4}", "a", "h", "s", "a", "n");
If you want to use StringBuilder, here is the code for you:
StringBuilder sb = new StringBuilder();
 
sb.Append("a");
sb.Append("h");
sb.Append("s");
sb.Append("a");
sb.Append("n");
 
string str = sb.ToString();
The above two examples will use the same instance of the string every time.

Use Conditional Attributes When You Need Them

Conditional attributes are very helpful when you want to do something only for the debug version. I know something came into your mind, the #if/#endif block. Yes, you can use the #if/#endif blocks to do something specific to the debug version like tracing or printing something to the output screen. Then why shouldn’t we use them? Of course, you can do that. But, there are some pitfalls. Suppose you wrote the following code:
private void PrintFirstName() 
{ 
    string firstName = string.Empty; 
    #if DEBUG 
    firstName = GetFirstName(); 
    #endif 
    Console.WriteLine(firstName); 
}
In this case, it will work perfectly while in debug mode. But, see the other side. When it goes to production, the GetFirstName() will never get called and hence it will print an empty string. That will be a Bug in your code. So, what to do? We can use the Conditional Attribute to overcome this issue. Write your code in a method and set the attribute of type Conditional with DEBUG string. When your application runs in debug mode, it will call the method and in other case, it will not. Let’s see the code here:
[Conditional(“DEBUG”)]
private void PrintFirstName()
{
    string firstName = GetFirstName();
    Console.WriteLine(firstName);
}
The above code actually isolates the function with the Conditional attribute. If your application is running under debug build, it will load the PrintFirstName() into memory on the first call to it. But when it will go to production build (i.e. release build) the method will never get called and hence it will not be loaded into memory. The compiler will handle what to do once it gets the conditional attribute to the method. Hence, it is always advisable to use the conditional attribute instead of the #if pragma blocks.
[Conditional(“DEBUG”)]
[Conditional(“TRACE”)]
private void PrintFirstName()
{
    string firstName = GetFirstName();
    Console.WriteLine(firstName);
}
Also, if you want to set multiple conditional attributes, you can do that by adding multiple attributes as shown above.

Use ‘0’ (zero) as Default Value Enum Value Types

While we write the enum definition, sometime we miss to set the DEFAULT value to it. In that case, it will set automatically as 0 (zero).
public enum PersonType 
{ 
    Customer = 1 
}
 
class Program 
{ 
        static void Main(string[] args) 
        { 
            PersonType personType = new PersonType(); 
            Console.WriteLine(personType); 
    } 
}
For example, the above code will always print 0 (zero) as output and you have to explicitly set the default value for it. But if we change it a bit and add the default value, it will always print the default value instead of 0 (zero).
public enum PersonType 
{ 
    None = 0, 
    Customer = 1 
}
 
class Program 
{ 
        static void Main(string[] args) 
        { 
            PersonType personType = new PersonType(); 
            Console.WriteLine(personType); 
    } 
}
In this case, it will print “None” to the output screen. Actually the system initializes all instances of value type to 0. There is no way to prevent users from creating instance of value type that are all 0 (zero). Hence, it is always advisable to set the default value implicitly to the enum type.

Always Prefer the foreach(…) Loop

The foreach statement is a variation of do, while or for loops. It actually generates the best iteration code for any collection you have. When you are using collections, always prefer to use the foreach loop as the C# compiler generates the best iteration code for your particular collection. Have a look into the following implementation:
foreach(var collectionValue in MyCollection)
{
    // your code
}
Here, if your MyCollection is an Array type, the C# compiler will generate the following code for you:
for(int index = 0; index < MyCollection.Length; index++)
{
    // your code
}
In future, if you change your collection type to ArrayList instead of Array, the foreach loop will still compile and work properly. In this case, it will generate the following code:
for(int index = 0; index < MyCollection.Count; index++)
{
    // your code
}
Just check the for condition. You will see a little difference there. Array has Length property and hence it generated code which calls the Length. But in case of ArrayList, it replaced the Length with Count, as ArrayList has Count which does the same thing. In other scenario, if your collection type implements IEnumerator, it will generate a different code for you. Let’s see the code:
IEnumerator enumerator = MyCollection.GetEnumerator();
 
while(enumerator.MoveNext())
{
    // your code
}
Hence, you don’t have to think which loop to use. The compiler is responsible for that and it will choose the best loop for you. One more advantage of foreach loop is while looping through the Single Dimensional or Multi Dimensional array. In case of Multi Dimensional array, you don’t have to write multi line for statements. Hence, it will reduce the code you have to write. The compiler internally will generate that code. Thus, increases your productivity.

Properly Utilize try/catch/finally Blocks

Yes, properly utilize the try/catch/finally blocks. If you know that the code you wrote may throw some Exception, use the try/catch block for that piece of code to handle the exception. If you know that, the fifth line of your 10 lines code may throw exception, it is advisable to wrap that line of code only with the try/catch block. Unnecessary surrounding lines of code with try/catch will slow down your application. Sometimes, I noticed people surrounding every method with try/catch block which is really very bad and decreases the performance of the code. So from now, use it only when it is required. Use the finally block to clean up any resources after the call. If you are doing any database call, close the connection in that block. The finally block runs whether your code executes properly or not. So, properly utilize it to cleanup the resources.

Catch Only that Exception that You Can Handle

It is also a major one. People always use the generic Exception class to catch any exception which is neither good for your application nor for the system performance. Catch only those which you expect and order it accordingly. Finally at the end, if you want, add the generic Exception to catch any other unknown exceptions. This gives you a proper way to handle the exception. Suppose, your code is throwing NullReferenceException or ArgumentException. If you directly use the Exception class, it will be very difficult to handle in your application. But by catching the exception properly, you can handle the problem easily.

Use IDisposable Interface

Use IDisposable interface to free all the resources from the memory. Once you implement IDisposable interface in your class, you will get a Dispose() method there. Write code there to free the resources. If you implement IDisposable, you can initialize your class like this:
using (PersonDataSource personDataSource = DataSource.GetPerson())
{
    // write your code here
}
After the using() {} block, it will call the Dispose() method automatically to free up the class resources. You will not have to call the Dispose() explicitly for the class.

Split your Logic in Several Small and Simple Methods

If methods are too long, sometimes it is difficult to handle them. It is always better to use a number of small methods based upon their functionality instead of putting them in a single one. If you break them in separate methods and in future you need to call one part, it will be easier to call rather than replicating the code. Also, it is easier to do unit testing for the small chunks rather than a big code. So, whenever you are writing a piece of code, first think of what you want to do. Based upon that, extract your code in small simple methods and call them from wherever you want. In general, a method should never be more than 10-15 lines long.

DotNetFunda.com on mobile Winners Win Prizes Winners & Prizes Announcements Like us on Facebook Top Articles Authors Mon, 25-Jun-2012 Authors All Time Authors SheoNarayan 31050 Karthikanbarasan 12250 Vishvvas 10000 Latest members | More ... (Statistics delayed by 5 minutes) Ads Articles Categories .NET Framework Articles ADO.NET Articles ASP.NET Articles ASP.NET AJAX Articles ASP.NET MVC Articles Azure Articles Best Practices Articles BizTalk Server Articles C# Articles CMS Articles CSS Articles Error and Resolution Articles F# Articles HTML 5 Articles IIS Articles JavaScript Articles jQuery Articles LightSwitch Articles LINQ Articles Management Articles OOPS Articles Others Articles Pattern and Practices Articles PowerShell Articles SEO Articles SharePoint Articles Silverlight Articles Sql Server Articles VB.NET Articles Visual Studio 2010 Articles WCF Articles Web Analytics Articles Windows Forms Articles Windows Phone Articles WPF Articles WWF Articles XML Articles Advertisements Basic Concepts of OOP: Encapsulation and Inheritence

In this article i would like to describe the people what are the basic concepts of Object Oriented Programming
The OOP stands on the following three pillars.

  1. Object &Class (Encapsulation)
  2. Inheritance
  3. Polymorphism

1 Object & Class (Encapsulation): 

       

         Object:


The Object is an Instance in programming language which is made by inspiring from the real world which contains some properties and methods.

Lets take an example of a person(object) from the real world.

A person is an object, as i told you before that an object could have methodes(behaviour)& properties so here person(object) could have some properties like his black hair,fair color,tall,and so on..Simillarly it could have the methodes like Eat,Run,Play,Sleep and so on..All these properties & methodes are kept stored in a seperate class.
          

         Class:


A class is basically a container where object lies..In programming we define all the properties&methodes in a seperate class while we make object of that class in main class... It means we generate the objects from main class, lets have a look..

class cat
{
   public void eat()
         {
           console.writeline("cat eats mouse");
          }
    public void walk()
          {
            console.writeline("It walks slowly...");
          }
}
Here we have defined a class and in 'class cat' " public void eat() " and " public void walk() " are methods.now we make an object in main class and call these methods...
static void main ()
{
   cat mycat = new cat();
    mycat.eat();
    mycat.walk();
    console.readline();
}
This is the main  class in which we make an object named mycat of the classs cat.. after making the cat's class object we can call its methods&properties by writting "mycat." when we put dot after the object it calls all the methodes & properties from the related class...

Encapsulation in OOP?


Encapsulation is the word which came from the word "CAPSULE" which to put some thing in a kind of shell. In OOP we are capsuling our code not in a shell but in "Objects" & "Classes".  So it means to hide the information into objects and classes is called Encapsulation.


2 Inheritance:


The Inheritance is one of the main concepts of oop.Inheritance is just to adobe the functionality (methods & properties) of one class to another. This simple term is known as Inheritance.  

Lets have a look of code
public class cat
{
   public void eat()
   {
      console.writeline("cat can eat");
    }
   public void walk()
   {
    console.writeline("cat can walk");
   }
}
now we make another class of another cat and we inherit the methods of the first class to the new class.Do remember in programming we inherit one class to another by coding " : " colon between the parent and child class.
Lets have a look.. 
public class EgyptianCat : cat
{
  public void jump()
  {
     console.writeline("Egyptian cat can jump"); 
  }
 public void bite()   {     console.writeline("Egyptian cat can not bite");     } }
static void main()
{
cat mycat=new cat();
mycat.eat();
mycat.walk();
EgyptianCat yourcat=new EgyptianCat();
yourcat.eat();
yourcat.walk();
yourcat.jump();
yourcat.bite();
console.readline();
}

this is the code in main class in which we are inheriting the class EgyptianCat to the class cat, so that the new class becomes the child class of the first class which is now called the parent class.

Basic Concepts of OOP : Polymorphism

 In this article i am describing Polymorphism for those who want to make their concepts clear.

Polymorphism

The word Polymorphism means of many forms.In programming this word is meant to reuse the single code multiple times. In object oriented programming its a big question that why the Polymorphism is done, what is the purpose of it in our code?

There are lots of people who don't even know the purpose and usage of Polymorphism.Polymorphism is the 3rd main pillar of OOP without it the object oriented programming is incomplete. Lets go in the depth of Polymorphism.

Why Polymorphism is done in OOP?

     
Its obvious that when we do inheritance between two classes, all the methods and properties of the first class are derived to the other class so that this becomes the child class which  adobes all the functionality of base class.It can also possesses its own separate methods.

But there is a big problem in inheriting the second class to the first class as it adobes all the methods same as the base class has,which  means that after inheritance both(base class& child class) have the methods of same name and same body as shown in this example:~

____Base Class___

public class fish
{
  public void eat()
   {
        console.writeline("fish eat");
    }
  public void swim()
   {
          console.writeline("fish swim");
    }
  }


______Derived Class______

class Dolphen:fish
{

  public void eat()
   {
        console.writeline("fish eat");
    }
  public void swim()
   {
          console.writeline("fish swim");
    }
}


In this example it is clear that when we Inherit two classes, all the methods with the same name and same body are adobed by the derived class as shown above.Both methods have the same name but if we change the body of the second method then it makes Compiler disturb whether to compile base class method or derived class's
method first... 

Lets have a look of this code..

____Base Class___

public class fish
{
  public void eat()
   {
        console.writeline("fish eat");
    }
  public void swim()
   {
          console.writeline("fish swim");
    }
  }


______Derived Class______

class Dolphin:fish
{

  public void eat()
   {
        console.writeline("Dolphin can eat");
    }
  public void swim()
   {
          console.writeline("Dolphin can swim");
    }
}


In this example we have changed the body of the methods of Derived class.Now this will make the Compiler disturb to compile which method first,because they both have same name but different bodies.
To remove this problem and to tell the compiler that which method is to be executed we need to use Polymorphism.


How the Polymorphism is done?

        
Polymorphism is used to remove the problem which is shown in the above code.It is done not by changing the name of the methods of both base & derived class.Infect it is done by adding the "virtual" keyword before the base class method, and the "override" keyword before the derived class method.As shown in this exmple:
 
____Base Class___

       
public class fish
        {
            public virtual void eat()
            {
                Console.WriteLine("fish eat");
            }
            public virtual void swim()
            {
                Console.WriteLine("fish swim");
            }
        }    
 

______Derived Class______

class Dolphin : fish
        {

            public override void eat()
            {
                Console.WriteLine("Dolphin can eat");
            }
            public override void swim()
            {
                Console.WriteLine("Dolphin can swim");
            }
        }

This is actually the Polymorphism in which we write virtual keyword with the base class method and we write override keyword with the derived class method as we did. It helps the compiler to select the method to be executed.

Here is the complete code in which Polymorphism has been applied.

class Program
    {
        public class fish
        {
            public virtual void eat()
            {  }
            public virtual void swim()
            { }
            public virtual void dive()
            {}

        }
       public class Dolphin : fish
         {
            public override void eat()
            { Console.WriteLine("Dolphin eats Plants"); }
            public override  void swim()
            { Console.WriteLine("Dolphin swims quickly"); }
            public override  void dive()
            { Console.WriteLine("Dolphin dive deeply "); }
           public void dance()
            { Console.WriteLine("Dolphin can Dance"); }

        }
        public class Shark : fish
        {
            public override  void eat()
            { Console.WriteLine("Shark eats dead animal"); }
            public override  void swim()
            { Console.WriteLine("Sharks swim fastest than Dolphin"); }
            public override  void dive()
            { Console.WriteLine("Sharks Dive deeper than Dolphin"); }

            public void kill()
            { Console.WriteLine("Shark kills Others"); }

        }
        
        static void Main(string[] args)
        {
            Dolphin D = new Dolphin();
            D.dance();
            D.dive();
            D.eat();
            D.swim();
            Shark S = new Shark();
            S.kill();
            S.dive();
            S.eat();
            S.swim();
            Console.ReadLine();
        }
    }

Regular Expressions in ruby

Regular Expressions in ruby :

A Regexp is a Ruby object representing a RegEx or "regular expression". So what exactly is a "regular expression"? It is a sort of string that can be used to match against another string. You could think of it as a template or a set of rules that a string can be compared to. Creating a Regexp object is much like creating a string, except that you use the forward slash to delimit it, rather than quote marks.
r = /my regular expression/

Alternatively, you can use this notation (you seem to be able to use any punctuation, just like %q for a string and %w for a word array):
r = %r|my regular expression|
r = %r
r = %r=my regular expression=

That regular expression will just match the string "my regular expression", anywhere in a string. The power of regular expressions lies in their use of wild cards, as we will see later.

Several standard Ruby methods take Regexp objects, but the most basic use is a simple comparison. There are two ways to do that; using the =~ operator or the match method in String. Both can be used either way around:
s = 'Here is my string'
r = /s my/
s.match r
r.match s
s =~ r
r =~ s

The difference is that the match method returns a MatchData object if a match is found, while the =~ operator gives the position of the match. However, the special variable $~ holds the MatchData for the last Regexp comparison performed, so this information is still available (personally, I do not like the built-in globals; if you want the MatchData object, use the match method, and everyone else with have a better idea of what you are doing). See later for more on MatchData.

So what can we put into a regular expression? There is a variety of options allowing you to specify your template as broadly or as narrowly as you want.
. any character except newline
[ ] any single character of set
[^ ] any single character NOT of set
* 0 or more previous regular expression
*? 0 or more previous regular expression (non-greedy)
+ 1 or more previous regular expression
+? 1 or more previous regular expression (non-greedy)
? 0 or 1 previous regular expression
??
| alternation
( ) grouping regular expressions
^ beginning of a line or string
$ end of a line or string
{m,n} at least m but most n previous regular expression
{m,n}? at least m but most n previous regular expression (non-greedy)
\1-9 nth previous captured group
\A beginning of a string
\b backspace(0x08)(inside[]only)
\b word boundary(outside[]only)
\B non-word boundary
\d digit, same as[0-9]
\D non-digit
\S non-whitespace character
\s whitespace character[ \t\n\r\f]
\W non-word character
\w word character[0-9A-Za-z_]
\z end of a string
\Z end of a string, or before newline at the end
\/ forward slash


Some simple examples
Here are some examples to get us going.
# Simple pattern matches to dog
p1 = /dog/
p (p1 =~ 'cat-dog') # => 4
p (p1 =~ 'cat-doggy') # => 4
p (p1 =~ 'cat-dig') # => nil
p (p1 =~ 'cat-fox') # => nil

# Pattern matches to d, any letter, then g
p1 = /d\wg/
p (p1 =~ 'cat-dog') # => 4
p (p1 =~ 'cat-doggy') # => 4
p (p1 =~ 'cat-dig') # => 4
p (p1 =~ 'cat-fox') # => nil

# Pattern matches to d, any vowel, then g
p1 = /d[aeiou]g/
p (p1 =~ 'cat-dog') # => 4
p (p1 =~ 'cat-doggy') # => 4
p (p1 =~ 'cat-dig') # => 4
p (p1 =~ 'cat-fox') # => nil

# Pattern matches to dog at end of string
p1 = /dog\Z/
p (p1 =~ 'cat-dog') # => 4
p (p1 =~ 'cat-doggy') # => nil
p (p1 =~ 'cat-dig') # => nil
p (p1 =~ 'cat-fox') # => nil

# Pattern matches to d, anything other than o or u, then g
p1 = /d[^ou]g/
p (p1 =~ 'cat-dog') # => nil
p (p1 =~ 'cat-doggy') # => nil
p (p1 =~ 'cat-dig') # => 4
p (p1 =~ 'cat-fox') # => nil


The MatchData object
If you bracket sections of your Regexp, you can then "capture" these subsections. Each subsection can be accessed as though the MatchData object as an array, with the first element being the entire matched string (though methods like each cannot be used). Use the offset method to determine the position in the string for each group. Here it is in action:
s = "Here is a string with http://www.mydomain.com/path/to/mypage.html in it"
r = /http:\/\/([a-z.]*)(\/[a-z]*)*(\/[a-z]*.html)/i
m = r.match s
p m.string
p m.pre_match
# => "Here is a string with "
p m.post_match
# => " in it"
p m[0]
# => "http://www.mydomain.com/path/to/mypage.html"
p m.offset(0)
# => [22, 65]
p m[1]
# => "www.mydomain.com"
p m.offset(1)
# => [29, 45]
p m[2]
# => "/to"
p m.offset(2)
# => [50, 53]
p m[3]
# => "/mypage.html"
p m.offset(3)
# => [53, 65]
p m[4]
# => nil
#p m.offset(4)
# => IndexError
p m.length
# => 4
p m.size
# => 4

If you want an actual array, use to_a or captures (the latter includes only the capture groups, the former also has the entire match as the first element).
m.captures.each { |e| p e }
# => "www.mydomain.com"
# => "/to"
# => "/mypage.html"
m.to_a.each { |e| p e }
# => "http://www.mydomain.com/path/to/mypage.html"
# => "www.mydomain.com"
# => "/to"
# => "/mypage.html"

I was surprised to find that you can only capture as many subsections as you have brackets. Even though the Regexp matches one subsection to two parts of the URL ("/path" and "/to"), only the last one appears in the array.

MatchData API
http://www.ruby-doc.org/core/classes/MatchData.html

Shortcut to capture groups
If you only want to pick one section out from a string, there is a quick way to do it. Both of these will pick out a number that follows a space, but the second way is much more conmcise.
# The usual way
md = s.match(/ ([0-9]+)/)
p md.nil? ? nil : md[1]

# The quick way
p s[/ ([0-9]+)+/, 1]
Note that for the first method we have to check for nil (no match is found), otherwise you will throw an error, as you are calling [] on nil. The quick way just returns nil if there is no match.

Back-references to capture groups - or not
A captured group can be refered to later in the pattern. Here is an example:
pattern = /aa(\d+)-\1/
pattern =~ 'aa1234-1234' # => 0
pattern =~ 'aa1234-1233' # => nil

The pattern requires at least one digit inside the brackets. This is the capture group. The backslash-one refers back to this group, and requires that the exact same number is repeated.

Note that capture groups number from one, rather than zero.

You may not want to have back-references to your capture group (remembering that you are limited to only 9 back-references). In the next example, question-mark-colon is used to indicate that we want to capture a group, but not to count it for back reference. We are looking for three groups of numbers in the pattern. The third should be identical to the second, but by marking the first as not counted, we can use \1 instead of \2. This trick allows you to have any number of captures, despite being limited to only nine back references.
pattern = /(?:\d+)-(\d+)-\1/
s = 'bird-cat-12-654-654-otter'
match = pattern.match s
match.to_a.each { |e| p e }
# => "12-654-654"
# => "654"
# => "done"

If you use the String.scan method, it splits a string into an array, each member of which matches the given pattern. If the pattern includes a capture group, then it is the part that is captured that goes into the array. However, if you use ?: yoiu can stop that behavior, to get the whole match (or another capture).

Multiple matches
Often you want to match multiple occurances.
\d Match exactly one digits
\d? Match one or zero digits
\d* Match zero or more digits
\d+ Match 1 or more digits
\d{2,5} Match between 2 and 5 digits
aeiou* Match "aeio" followed by any number of "u"
[aeiou]* Match any number of vowels
(aeiou)* Match any number of sequences of "aeiou"


Greedy vs non-greedy
A greedy match will try to match against as many characters as possible, while a non-greedy will match against as few as possible. Here is a simple example to illustrate:
s = "Here another string"
greedy = /[a-z]* [a-z]*/
non_greedy = /[a-z]*? [a-z]*?/
p greedy.match(s)[0] # => "ere another"
p non_greedy.match(s)[0] # => "ere "

The * will match against a number (or zero) of the preceding, so in the two Regexp objects, they will look for a match against a group of letters, then a space, then a group of letters. The difference is the second has the ?, which makes the * non-greedy.

In both cases they ignore "H" as it does not fit, then they find a match for "e". The match continues, as both are allowed a variable number of letters, and they then match the space. Finally each can have a variable number of lower case letters. The non-greedy version aims for the fewest - in this case zero. The greedy version grabs all it can, so gets "another".

Alternatives
For a set of alternative characters, put them inside square brackets. For sequences, use curved brackets, separated by vertical bars.
[aeiou] Match any one vowel
(dog|cat) Match either "dog" or "cat"


Building Regexp objects dynamically
You can use #{} when defining a Regexp, just as you can for a double-quoted string. Here is a real example that adds two new methods to the String class (the Rails API already adds them, by the way):
class String
def starts_with? sub
match(/^#{sub}/)
end

def ends_with? sub
match(/#{sub}$/)
end
end

The argument sent to the method gets incorporated into the Regexp. Note how ^ and $ are used to anchor the match to the start of the end of the string respectively.

Case sensitivity and other options
You can change the way the pattern matches either by appending a control code, to change the whole pattern, or using extended patterns (borrowed from Perl). These are things you can insert into a pattern inside brackets, following a question mark. For example, you can use i and -i to turn case sensitivity on and off.
# Case sensitive by default
pattern1 = /fox-cat-dog/
pattern1 =~ 'fox-cat-dog' # => 0
pattern1 =~ 'fox-CaT-dog' # => nil
pattern1 =~ 'fox-CaT-doG' # => nil

# Whole pattern modified, case insensitive
pattern2 = /fox-cat-dog/i
pattern2 =~ 'fox-cat-dog' # => 0
pattern2 =~ 'fox-CaT-dog' # => 0
pattern2 =~ 'fox-CaT-doG' # => 0

# Pattern behavior modified within the pattern
# case sensitivity turned off then back on
pattern2 = /fox-(?i)cat-(?-i)dog/
pattern2 =~ 'fox-cat-dog' # => 0
pattern2 =~ 'fox-CaT-dog' # => 0
pattern2 =~ 'fox-CaT-doG' # => nil

# Pattern behavior modified within the pattern
# case sensitivity turned off for substring
pattern2 = /fox-(?i:cat)-dog/
pattern2 =~ 'fox-cat-dog' # => 0
pattern2 =~ 'fox-CaT-dog' # => 0
pattern2 =~ 'fox-CaT-doG' # => nil


The full list of options is:
/i case insensitive
/m multiline mode - '.' will match newline
/x extended mode - whitespace is ignored
/o only interpolate #{} blocks once
/[neus] encoding: none, EUC, UTF-8, SJIS, respectively

The last two can, I think, only be used to modify the whole pattern.

Comments
There are various other options using the brackets-question-mark notation. You can embed a comment:
pattern2 = /cat(?#comment)dog/
pattern2 =~ 'catdog' # => 0

This makes more sense with the x option just mentioned, which causes the pattern to ignore whitespace, and so allow formatting and comments like this:
pattern1 = /\d\d\d (?# Looking for three digits )
- (?# followed by a hash )
\d\d\d (?# and abother three digits )
/x
p pattern1.match('578 123-678ref 567')[0]
# => "123-678"


Looking ahead
You can also look ahead at what follows, without getting the next bit including in your match. You can check that pattern is either there or is absent, as show in this example. In the first instance, pattern1 looks for three numbers follwed by "ref", but the resultant match has only the three numbers. Then pattern2 looks for three numbers not followed by a space.
pattern1 = /\d\d\d(?=ref)/
pattern2 = /\d\d\d(?! )/
pattern3 = /\d?(?! )/
p pattern1.match('578 123 678ref 567')[0]
# => "678"
p pattern2.match('578 123 678ref 567')[0]
# => "678"
p pattern3.match('578 123 678ref 567')[0]
# => "57"