C# Properties

C# Properties

Advertisements

This subject is related to encapsulation principle, you can find more about it here.

Properties are an extension of fields and are accessed using the same syntax. They use accessors through which the values of the private fields can be read, written or manipulated. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

Accessors

There are two basic types of accessors

set {accessor-body}
get {accessor-body}

Set allows to assign value to the field, called write method. It uses variable key word that represents the value that is assigned.

Get allows to return the value of the field, read method. Get must  return a value;

Field

Private field will prevent user from changing the data directly. This is concept of encapsulation. Field naming convention is to use underscore as prefix and start with low case letter.

 

public class MyClass
{
    // this is a field.  It is private to your class and stores the actual data.
    private string _myField;

    // this is a property.  When you access it uses the underlying field, but only exposes
    // the contract that will not be affected by the underlying field
    public string MyProperty
    {
        get
        {
            return _myField;
        }
        set
        {
            _myField = value;
        }
    }
}

 

Properties can be self implemented using

    public int Number{ get; set; }

 

Properties Implementation

One of properties advantages is option of selecting which of read/write method will be available,  for example we can want to restrict access to variable, making it read only. This will not allow user to change the data. To do this we write only get method in implementation.

Another advantage of properties is ability to perform operations on data inside the accessors. Let’s say we want to assign only positive numbers

using System;

class Example
{
    int _id;
    public int Id
    {
	get
	{
          return this._id;
        }
         set
	    // We don't allow this to be a negative value
	    if (value < 0 )
	    {
		throw new Exception("Invalid number");
	    }
	    this._id = value;
	}
    }
}

 

Default Values

Automatic properties have support for default values much like fields.

  public int Id { get; set; } = 404; // Has default value.

 

To conclude, Using properties is a vary good habit. It can protect the fields from corruption by setting checks conditions in setter. Or it can help with reading the value, using getter implementation. Using properties we can change the values of private field without exposing it, which is part of encapsulation principle. In next articles I’ll cover  most important design patterns. Stay Awesome!

 

 

Multithreading

Imagine you need to write a program with a method that takes ages to execute, if you create this in procedural way, the console will freeze and user will be unable to do anything.  This problem can be solved by using multiple cores of processor unit. Assign long task to a single core other than the main one.

Today I’ll demonstrate a simple example of multi-threading process to show you how to deal with this type of situations.

Lets analyse simple example

using System;
//Multi Threading is a part of System.Threading library.  
using System.Threading;

public class Test
{
    static void Main()
    {
      
        Thread thread = new Thread(TaskMethod);
        thread.Start(); // kicks new tread
        
        for (int i=0; i < 5; i++)  //kicks another thread
        {
            Console.WriteLine ("Main thread: {0}", i);
            Thread.Sleep(1000);   //sleep 1s
        }
    }
    
    static void TaskMethod()
    {
        for (int i=0; i < 10; i++)
        {
            Console.WriteLine ("Other thread: {0}", i);
            Thread.Sleep(500); //sleep 0.5s
        }
    }
}

This example demonstrates the outcome of two simultaneous threads. We invoke our thread in main function and in the next line we start another similar task, running at the same time. Lets take a look at the console output.

Thread

We can see that as we expected both loops are running together without any delay.

Recap:

  • Threads can be declared by passing function into it.Function name does not contains parenthesis.
Thread thread = new Thread(TaskMethod);
  • Thread is executed by threat.Start() method
  • All thread related methods are inside System.Threading library.

This concept involves technical knowledge of CPU but implementation of treads is not that difficult, now when you know the basics, we can move to real world examples. In next part I’ll show you how to deal with an situation I presented in first paragraph.Stay Awesome!