Guidelines for Properties in C#: Property vs Field

October 7th, 2009

This post is a summary of guidelines and rules for choosing between Property and Field in C# language. In general fields - should be used to store internal state of an object and should not be public. You will never (except maybe few exceptions) find public fields in base .NET class library.

On the contrary Property should expose distinguishing feature of an object either public or protected. There should not be much use of the private properties as they are points of confusion with a fields.

 

Property not always represents storage of data values - it may be evaluated at accessing. That is why property might expose side-effect which will never happen while using fields, for example, consider following code snippet:

 

MyClass o = new MyClass();

o.Property = “Hello”;

 

return o.Property == “Hello”;

 

One would expect this to return true, but as seen from example it would not be always the case. Consider this:

 

string Property

{

  get { return string.Empty; }

  set { }}

 

Ideally following rule should be considered while designing public property: immediate access to the property getter after setting some value should return this value.

 

Often properties are used to implement change notification via INotifyPropertyChanged interface and I would recommend to follow such pattern initially described to me by Denis Vuyka (notice how property name passed to OnPropertyChanged handler, thus in future it will ease maintaining code during property renaming) :

 

 

public class MyClass : INotifyPropertyChanged

{

    private string message;

 

    public string Message

    {

      get

      {

        return message;

      }

      set

      {

        if (object.Equals(message, value)) return;

 

        message = value;

        OnPropertyChanged(() => this.Message);

      }

    }

 

    #region INotifyPropertyChanged Members

 

    public event PropertyChangedEventHandler PropertyChanged;

 

    protected virtual void

        OnPropertyChanged(

      Expression<Func<object>> propertyFunc)

    {

      if (PropertyChanged != null)

        PropertyChanged.Invoke(this, new

          PropertyChangedEventArgs(

            ((MemberExpression)propertyFunc.Body)

               .Member.Name));

    }

    #endregion

  }

 

Another common side effect which might be exposed by property - is a modification of the object’s state during getting value:

 

public class Wrong

{

 

  string newText = null;

 

  public string Text

  {

    get

    {

       if (newText == null)

         newText = GetTextConstant();

 

       return newText;

    }

 

    ….

  }

 

}

 

This behaviour may lead to unexpected results. Consider example of WinForm multi-threaded application whereas background thread access objects in Read-Only manner, i.e. it uses only property getters. UI in main thread subscribes to all objects changes for updating. Now, if getter in background thread will cause change in state of the instance, it will raise change event. UI update handler will be invoked in background thread which may lead to application crash.

 

So, now we are ready to formulate another fundamental rule: accessing property getter should never lead to object’s state change.

S# puzzle game Cli-Q

June 25th, 2009

Cli-Q is a space-travel puzzle game on Silverlight advertising S# language as scripting language for games.

 Cli-Q Logo

Cliq-Q exposes simple object model allowing developer easily extend functionality, create new levels and in future - new types of gaming objects.

The game field contains player object - white circle, win point - orange circle and a number of static obstacles and dynamic objects. Static obstacles simply stops player object from further movement, while dynamic objects - such as triangles may change direction of further movement:

Game field

Play Now!

On-Line calculator based on Script.NET for Silverlight 2.0

April 7th, 2009

As I’ve promised few weeks ago there is now Silverlight version of Script.NET. I’ve searched through Web and I think this is a first fully functional scripting engine for Silverlight. If this is wrong - please notify me at piter.protsyk@gmail.com and I will correct this information. Please also note that my understanding of scripting is quite different from those of Microsoft’s view with regards of IronPython and IronRuby. Both of these languages emits IL code and generates dynamic assemblies/method which then executed on .NET. In contrast Script.NET is a pure interpreted language which has a number of advantages.

To proof a concept of Script.NET for Silverlight I’ve created the On-Line calculator on its basis:

Silverlight 2.0 Calc

 Silverlight 2.0 Calculator Based on Script.NET

Sources & Binaries

Enjoy!

It can execute any valid Script.NET expression and has access to only one .NET type - Math.

Script.NET for Compact Framework

March 17th, 2009

Today I am glad to announce the first version of Script.NET which is able to run on Compact Framework (3.5).

It could be downloaded by the following link:

Script.NET for CF.

Also I would like to thank Steve Higgins without whom CF version of Script.NET most probably would not appear.

Meantime, in the nearest future I will produce a Silverlight version of Script.NET.

Synchronuos start of many instances of the same process

February 27th, 2009

Suppose you need to start 5 instances of the same process simultaneously. There are no problems until those process does not use resources exclusively. For example they are trying to write to the same log file at the same time:

config1.GIF

In this case you will need to synchronize them in a some way. You may want to make those processes to run some sections of code in a mutually exclusive mode:

config2.GIF

 This may be naturally achieved by introducing a mutex synchronization. The sample below shows this approach on practice: mutex.zip

To see the results start several instances of this application at the same time, and the release mutex lock by pressing any key on the application’s console. You will see how other processes will react on this event:

synchronizedstart.JPG