[C#]Creating and using .dll files


Yesterday in my college during System Software class we were learning about Dynamic Loaders. And the lecturer said some stuff about DLL files. Most people dont realize what a dll file is and how simple it is to create and use one in their programs. I came across programming dlls when I was learning C#.NET. DLL files are just code files that cant run alone. They support other programs. For instance you can store some classes in a dll file and you can link this file to any number of programs you want. And whenever your program wants the class it can just call the dll and it will be loaded @ runtime. Using dlls also reduces the amount of space your code occipies on disk since you are sharing the same dll among many programs. And it also allows modular programming. Anyway, I need not explain much about the advantages of using dlls since its well documented already on the web. You can google it and find more about it yourself!

Now Im gonna teach you how to create your own dll file and use it in your programs!  Some might have seen the FLAMES app that I coded in C#. It actually uses a dll file to store the class that does the computation work. And has the GUI stuff separately.

Continue reading

Interfaces and Abstract Classes: Clearing the fog…..


There are two very important concepts or features in many Object Oriented Programming Languages that allow programmers to create a common interface to communicate with objects. They are Abstract Classes and Interfaces. They are fundamentally different but are used to provide the same functionality. Let us see about them separately and then we will see when to use an Interface and when to use an Abstract Class.

An Abstract Class is a class which does not provide concrete implementations (definitions) for its methods. Generally while creating a Class Hierarchy, we create a very general base class and derive these general members into a more specific Sub Class. I found the example in Paul and Harvey Deitel’s “C# for Programmers”  book very interesting and insightful.

A company wants to create an application to calculate salaries for the different types of employees it has, like Salaried Employees, Hourly Employee, Commissioned Employee. So basically you create a general Employee Class which will be abstract (to make a class Abstract just add the keyword ‘abstract’ before the keyword ‘class’) and put some general attributes and methods in it. But since the way the Salary is calculated differs from employee to employee, we can declare the Salary Calculation method as Abstract. When we declare a method as Abstract, we must not provide any concrete implementation for it (i.e) we must no provide definition for the method.

Java Syntax:

public abstract double salaryCalc();

C# Syntax:

public abstract double salaryCalc();

So now in the derived classes these methods can be “overridden” to provide employee-specific definitions/implementations.

Java Syntax:

public double salaryCalc() {

//definition

}

C# Syntax:

public override double salaryCalc() {

//definition

}

(Note: C# requires usage of  “override” keyword. In Java its optional to use “@Override” annotation above the method implementation)

Thus each derived class can provide its own implementation for the derived abstract method but all those methods will have the same signature/header/call syntax. So we provide uniform interface for accessing the methods of the derived class.

Speaking of providing common interface for accessing derived class, we can use a Class variable of the Abstract base class to polymorphically access the overridden methods of the derived classes. This is called “Subtype Polymorphism“. Abstract classes were created to make general base classes but they also serve as a basis for implementing Polymorphism.

But Polymorphism can also be implemented by another technique called Interfaces. Lets see about the Java and C# interface, a relatively new concept…

An Interface is similar to an Abstract Class, but differs in the fact that it provides absolutely no concrete implementation for any of its methods. Some may say an Interface is also a class. But its not. An Interface is not a class. Its like a contract that classes sign. When a class ‘implements’ an interface, it basically signs a contract saying that, “Ill provide definition for all the method declarations declared in the Interface”. Creating an interface is rather simple and similar to creating a class.

Java, C# Syntax:

public interface Employee {

double salaryCalc();

}

So now our employee specific classes can implement this interface and provide concrete definitions for the method salaryCalc(). In C#, syntax for implementing an interface is similar to that of inheriting a base class. But in Java instead of using the “extends” keyword which we use in order derive from a base class, we use the keyword “implements”.

And the classes that implement an interface can provide definitions for the interface methods just like creating a normal method. (i.e) There is no need to use the “override” key word (in case of C#). In Java however, its optional to include the ‘@Implements’ annotation above the method.

In the Abstract Class section, we implemented Subtype Polymorphism by creating  a Class Variable for base class and accessing the derived class instances/objects using that variable. Similar to that we can create an Interface Variable for the Interface and we can use that interface variable to refer the instances of the classes that implement that interface.

So now a question arises. Both abstract class and Interface provide same functionality and help implement polymorphism. So why do we need the new concept called Interfaces. There are two main reasons why we need both Interfaces and Abstract Classes.

The first reason is, In C# and Java, there is no such thing as ‘Multiple Inheritance’. This concept, which was included in languages like C++, caused lots of ambiguity and complexity and hence it was removed in the newer languages like C# and Java. And so a class can ‘extend’ or ‘inherit from’ only one base class. But there are some situations where you need something like multiple inheritance. So in those situations you may use an Interface. A class can implement ‘n number of Interfaces’

Id like to explain the second reason from the Polymorphism perspective. In polymorphism, you basically handle objects of multiple classes using a common Variable. But if you have only Abstract Class concept, only those classes that extend/inherit that abstract class can be handled using the common Variable (Class variable of the Abstract Base Class). But these classes that extend the Abstract Base class almost always come under the same category. (eg.) An employee Abstract Base class is extended by classes that represent some specific employees. An IO Device Base class is extended only by specific IO device classes. So if you have only Abstract Class concept, you can access multiple objects with a common variable only if these objects belong to the same class hierarchy of the Abstract Base class. In a sense you can deal only with related classes.

But if you want to handle instances of Classes which are unrelated with a common variable, then you need to use Interfaces. For eg: A company wants to develop an application that processes payments. But they want the same application to process payments to employees (Salaries) and payment to invoices. So we create two different class hierarchies, one for invoices and one for employees. And we will have to handle instances of these two hierarchies with a common variable. So to do this, we can create an interface that has the common method (say, getPaymentAmount() ) and make the two hierarchies implement this interface. Now we can create a variable for this interface and use it to access the instances of the two unrelated classes.

So use Abstract Class when you want to access instances of classes belonging to same Class hierarchy Polymorphically (using common variable) and use Interfaces when you want to access instances of different and unrelated class hierarchies Polymorphically (using common variable).

So these are the Abstract Class and Interface Concepts. So I hope this article gave you a clear idea about these two powerful concepts.

If you have any doubts, clarifications, suggestions please leave a comment below…..

Steve Robinson.

/* Class hierarchy example take from Paul and Harvey Deitel’s “C# for Programmers” 
UML Diagrams created using creately.com‘s online UML drawing application */

Creating Custom Events in C#


As we all know C# and other .NET languages are basically event driven. As soon as a event occurs the OS alerts the program and the program handles the signal using one of the defined handler functions. We have events that indicate mouse click, key press etc etc that can be included easily. We can also create custom events ourselves. We can define when the event gets triggered and where to handle the event.

Let us take the example of a modeless Dialog (Modeless form: A form the behaves independently and the user can switch between the child and parent forms. eg: Find Dialog Box). We have two forms. The parent form [Form1] opens the modeless form [Form2]. Let us communicate between these two forms using our custom event. We will create the event in the child form and will subscribe the parent form to the event so that when it is triggered the parent form will receive the EventArguments Object.

Let us first see the the Form2 Code:

////////////////////////////////////////////////////////////////////////////////////////////////////
//Form2.cs -Modeless
///////////////////////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

    //Creating of EventArgs for the custom Event
        public class MyEventArgs: EventArgs
        {
            private string message;

            public string Message
            {
                get { return message; }
                set { message= value; }
            }
        }

    //Creation of Event itself
        public event EventHandler<MyEventArgs> ButtonClicked;

    //Function that raises the Event and broadcasts it
        private void eventRaiser(UpdatedArguments e)
        {

            if (ButtonClicked!= null)  
                ButtonClicked(this, e);
        }

        private void button1_Click(object sender, EventArgs e)
        {   
            MyEventArgs newEvent=new MyEventArgs();//Creation of EventArgs Obj.
            newEvent.message= "SOS";
            eventRaiser(newEvent);
        }
    }
}

This code Basically contains three parts:

1. Custom Event Arguments Class Definition [Inherited from EventArgs]
2. Even Broadcaster Function
3. Function that raises the event

The code is rather Self Explanatory. We first create the Custom Event’s Arguments. We are just inheriting from EventArgs Class that contains all other functions. We need to include in our class only the messages and data that we need to pass as event arguments to the event handler.
Then we create the event and denote the arguments that the event will use It is of type event and it must be public. Then we create the function that will raise of Broadcast the event to all subscribed forms. It receives the event argument that need to be sent. It is a good practice to check whether the event is not null. Then the event is raised and the reference to this form and the event argument object is sent as parameters. Thus we have created a form that raises an event!

Now let us look at the parent form that receives the event and handles it.

//Form1.cs


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
        
  public Form1()
  {
  InitializeComponent();
  Form2 FirstNameForm = new Form2();
  //Event Subscription
  FirstNameForm.ButtonClicked+= new EventHandler<Form2.MyEventArgs>
                                         (FirstNameForm_ButtonClicked);
  FirstNameForm.Show();
  }
         
        //Event Handler
        void FirstNameForm_ButtonClicked(object sender, Form2.MyEventArgs e)
        {
            if (e != null)
                MessageBox.Show(e.Message);
        }
       

    }
}

As we can see, we have created the child form in the Constructor of the Parent form.
As soon as ” FirstNameForm.ButtonClicked+= ” is typed, the rest of the event subscription is suggested by Intellisense (if you are using Microsoft Visual Studio). The Event handler function is also declared by the IDE itself.
You just need to define e what you need to do after the event has been raised. In our case, we have printed the message passed as the argument using a message box.

Well, this is it. Lets summarize what we have done.
We have created a new form that operates as a modeless dialog box. We have defined our class that is inherited from EventArgs class that will be used to create event arguments function. We have created the event itself. Then we have created a function to broadcast the event along with the reference to the Form that raises the event and the event Argument object.
Then we have subscribed to the Event from the parent form. Then we have created the handler function that will be called once the event from the other form is raised.

This is a very good technique for inter-form communication. Lots of Internet tutorials ask us to make the controls in the parent form public so that it can be accessed from the other forms. But all that is rubbish. This method provides a clean way for interprocess communication. Use your creativity to use this technique wisely!

I have created a project to illustrate this. I have created two forms. In one form you can type a message and press Send Button and the message will be received in the other form. An Event is wired to raise when the Send is clicked and the other form is subscribed to this event and hence in the Event Handler in the Parent form, the message is processed.
LulzImg - Image Hosting for teh lulz

Project Link:

http://www.mediafire.com/?nz5elldxe0z6lia

Regards,
Steve Robinson.