Friday 11 July 2014

Passing information around - using an Interface

One aspect of C# which has room for improvement is that of inheritance. In C++, a class can inherit as many other classes as it needs to. This multiple inheritance is sadly lacking in C# - the most that can be inherited is a single class.

The way C# gets around this problem is by using interfaces. Interfaces are special - you can define methods in there, but that's about it. Think of it as a C header file - it contains the prototypes for functions but not the variables.

interface Isettings
{
    void loadsettings(bool group);
    void resetsettings();
    void saveSettings(bool group);
}

public class foo : Form, Isettings
{
   public foo()
   {
   }

   public void loadsettings(bool group)
   { 
  

Here, the class foo inherits the System.Windows.Form class as well as the Isettings interface (it happens to define the method properly here - but the interface can be used anywhere and as many interfaces can be inherited as well.

Another method is to simply define a class and then create a new instance of it in whatever other class needs it - this can be performed in one of two ways

public class common
{
   public int intro, meth, result, discuss, addition;
   public decimal final;
   public string date;
   public bool groups;
}

public class MainForm
{
   public MainForm()
   {
      this.InitializeComponent();
   }
   common data;
   // more code
}


I've not created a new instance of common here, just created a local pointer to it. If anything is used from this pointer which has not been given a value (for example if I did the following and result has not been defined int fish = result * 10;), then the final result may not be what is expected.

As it is a pointer, you're working on the stack and odd things happen when you're on the stack... If you change something, it's stored and everyone gets the change

The final method is a to create a new instance of a class

var settings = new XmlReaderSettings();

A completely new instance of the class XmlReaderSettings has been created here - the structure, methods and anything defined in XmlReaderSettings has been replicated in settings. If settings is changed, it does not change XmlReaderSettings

It is possible to pass either the pointer to the class or the instance of the class to another method in the same way as you would pass any other type

var settings = new XmlReaderSettings();
m.Text = some_function(settings);
//
private string some_function(XmlReaderSettings settings)
{
   //
}

No comments:

Post a Comment