Delving deeper into C# - Classes & Interfaces


Synopsis

In this lesson we will use a little measure conversion application which I wrote as an example.
This is application is slightly more advanced than string sort, which means we have a bunch of classes and interfaces to look at.
So what's the same and what's different in C# (assuming you know C++):

Points of interest

Constructors

public class LinearConverter : ScalingConverter,IConvert,IReversibleConverter
{
	public LinearConverter()
	{
	}
	public LinearConverter(double factor,double offset)			
		: base(factor)
	{			
		m_offset = offset;
	}
...
still named as the class, however no default parameters (no such concept in C#, use contructor overloads instead) and no initializer lists for members : all initializations are done in the body.
The call to base constructor (single inheritance, so there's only one) looks like base(...). The base keywork can be used anywhere to call base class's methods

A new creature : static constructor - do all the static member initializations there. Example:
public class C { 
  static int a;
  static C() {
    a = 0;
  }
}
In summary:

Access modifiers

For classes, members, interfaces etc.

Field modifiers

For classes, members, interfaces etc.
public class C
{
  public C()
  {
    a = new X(b);
  }
	
  private readonly X a;
  private const int b = 5;
}

In short use const for value type constants and use readonly for reference type (Object) constants.

Interfaces

Interfaces are defined similar classes , the subtle difference is that all methods are public and virtual and there's no need to specify it. So a typical interface definition look like this:
public interface IConvert
{
 double convert(double val);
 string formatFormula(string argument);
}
Then the class definition that implements the interface will look like: public class ScalingConverter : IConvert,IReversibleConverter
This class implements 2 interfaces.

Named overrides:
When you are implementing an interface you have 2 choices:
 1) just override the method as you would any virtual function: in this case the method will be accessible whether you
 have reference to a class itself or to an interface:
 public virtual double convert(double val)	  
 2) Use "Named override" like this 
  double IConvert.convert(double val)
 In this case the method will be visible only through a reference to an interface.
 This solves an important design problem from C++ where you needed to make you interface implementation methods always public
 which sometimes muddled the class interface making it too rich. 


to main .Net page

 Home    My LiveJournal    Professional    Photos    Hobbies    Friends  


Copyright (C) 2002, Ilia Tulchinsky
If you have any questions, bug reports, suggestions or just thoughts worth sharing contact me at ilia@tulchinsky.com.