Static Constructors

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
 
Static constructors have the following properties:

  1. A static constructor does not take access modifiers or have parameters.
  2. A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  3. A static constructor cannot be called directly.
  4. The user has no control on when the static constructor is executed in the program.
  5. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  6. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

Consider the following example for working of static constructors :

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static int x;
        static Program()
        {
            x = 14212;
        }

        static void function1()
        {
            Console.WriteLine(x);
        }

        static void Main(string[] args)
        {
   
          function1();
            Console.Read();
        }
    }
}

Static functions

Static functions are the functions which are not bounded by the space of any class. They are called directly without making an object from which class they belong. Following example demonstrate the things.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void function1()
        {
            Console.WriteLine("static methods")
        }

        void function2()
        {
            Console.WriteLine("non static method");
        }

        static void Main(string[] args)
        {
            function1(); // static methods called directly
            function2(); // will give error, because not static
            // in order to use function2, we need an object
            Program pr = new Program(); // object created
            pr.function2(); // function2 called
            Console.Read();
        }
    }
}

Destructors

Destructors are used by the .NET Framework to clean up after objects. In general, you don ’ t have to provide code for a destructor method; instead, the default operation does the work for you. However, you can provide specific instructions if anything important needs to be done before the object instance is deleted.
 
When a variable goes out of scope, for example, it may not be accessible from your code, but it may still exist somewhere in your computer ’ s memory. Only when the .NET runtime performs its garbage collection cleanup is the instance completely destroyed.
 
Don ’ t rely on the destructor to free up resources used by an object instance, as this may occur long after the object is of no further use to you. If the resources in use are critical, then this can cause problems. A Destructor is demonstrated as :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication1
{

    public class baseClass
    {
        public baseClass()
        {
            Console.WriteLine("baseClass Constructor");
        }
        ~baseClass() // defining desctuctors
        {
            Console.WriteLine("Destructor executes after pressing key");
        }
    }
    class Program
    {
        Program()
        {
            Console.WriteLine("inside main program class");
        }
        static void Main(string[] args)
        {
            baseClass a = new baseClass();
            Program pr = new Program();
            new Program(); // another way to call constructors
            Console.Read();
        }
    }
}

Properties and Fields

Properties and fields provide access to the data contained in an object. This object data is what differentiates separate objects, because it is possible for different objects of the same class to have different values stored in properties and fields.
 
The various pieces of data contained in an object together make up the state of that object. Imagine an object class that represents a cup of coffee, called CupOfCoffee . When you instantiate this class (that is, create an object of this class), you must provide it with a state for it to be meaningful. In this case, you might use properties and fields to enable the code that uses this object to set the type of coffee used, whether the coffee
contains milk and/or sugar, whether the coffee is instant, and so on. A given coffee cup object would then have a given state, such as ” Columbian filter coffee with milk and two sugars .”
 
Both fields and properties are typed, so you can store information in them as string values, as int values, and so on. However, properties differ from fields in that they don ’ t provide direct access to data. Objects can shield users from the nitty – gritty details of their data, which needn ’ t be represented on a one – to – one basis in the properties that exist. If you used a field for the number of sugars in a CupOfCoffee instance, then users could place whatever values they liked in the field, limited only by the limits of the type used to store this information. If, for example, you used an int to store this data, then users could use any value between – 2147483648 and 2147483647.
 
In general, it is better to provide properties, rather than fields, for state access, because you have more control over various behaviors. This choice doesn ’ t affect code that uses object instances, because the syntax for using properties and fields is the same.
 
Read/write access to properties may also be clearly defined by an object. Certain properties may be read – only, allowing you to see what they are but not change them (at least not directly). This is often a useful technique for reading several pieces of state simultaneously. You might have a read – only property of the CupOfCoffee class called Description , returning a string representing the state of an instance of this class (such as the string given earlier) when requested. You might be able to assemble the same data by interrogating several properties, but a property such as this one may save you time and effort. You might also have write – only properties operating in a similar way.
 
As well as this read/write access for properties, you can also specify a different sort of access permission for both fields and properties, known as accessibility . Accessibility determines which code can access these members — that is, whether they are available to all code (public), only to code within the class (private), or use a more complex scheme. One common practice is to make fields private and provide access to them via public properties. This means that code within the class has direct access to data stored in the field, while the public property shields external users from this data and prevents them from placing invalid content there. Public members are said to be exposed by the class.

What Is an Object

An object is a building block of an OOP application. This building block encapsulates part of the application, which may be a process, a chunk of data, or a more abstract entity.
 
In the simplest sense, an object may be very similar to a struct type such as those shown earlier in the book, containing members of variable and function types. The variables contained make up the data stored in the object, and the functions contained allow access to the functionality of the object. Slightly more complex objects might not maintain any data; instead, they can represent a process by containing only functions. For example, an object representing a printer might be used, which would have functions enabling control over a printer (so you can print a document, a test page, and so on).
 
Objects in C# are created from types, just like the variables you ’ ve seen already. The type of an object is known by a special name in OOP, its class . You can use class definitions to instantiate objects, which means to create a real, named instance of a class. The phrases instance of a class and object mean the same thing here; but note at this point that class and object mean fundamentally different things.

Object – Oriented Programming

Object – oriented programming is a relatively new approach to creating computer applications that seeks to address many of the problems with traditional programming techniques. The type of programming you have seen so far is known as functional (or procedural ) programming, often resulting in so – called monolithic applications, meaning all functionality is contained in a few modules of code (often just one). With OOP techniques, you often use many more modules of code, each offering specific functionality, and each module may be isolated or even completely independent of others. This modular method of programming gives you much more versatility and provides more opportunity for code reuse.
 
To illustrate this further, imagine that a high – performance application on your computer is a top – of – the – range racecar. Written with traditional programming techniques, this sports car is basically a single unit. If you want to improve this car, then you have to replace the whole unit by sending it back to the manufacturer and getting their expert mechanics to upgrade it, or by buying a new one. If OOP techniques are used, then you can simply buy a new engine from the manufacturer and follow their instructions to replace it yourself, rather than take a hacksaw to the bodywork.
 
In a more traditional application, the flow of execution is often simple and linear. Applications are loaded into memory, begin executing at point A, end at point B, and are then unloaded from memory. Along the way various other entities might be used, such as files on storage media, or the capabilities of a video card, but the main body of the processing occurs in one place. The code along the way is generally concerned with manipulating data through various mathematical and logical means. The methods of manipulation are usually quite simple, using basic types such as integers and Boolean values to build more complex representations of data.
 
With OOP, things are rarely so linear. Although the same results are achieved, the way of getting there is often very different. OOP techniques are firmly rooted in the structure and meaning of data, and the interaction between that data and other data. This usually means putting more effort into the design stages of a project, but it has the benefit of extensibility. After an agreement is made as to the representation of a specific type of data, that agreement can be worked into later versions of an application, and even entirely new applications. The fact that such an agreement exists can reduce development time dramatically. This explains how the racecar example works. The agreement here is how the code for the “ engine ” is structured, such that new code (for a new engine) can be substituted with ease, rather than requiring a trip back to the manufacturer. Conversely, it also means that the engine, once created, can be used for other purposes. You could put it in a different car, or use it to power a submarine, for example.
 
As well as providing an agreed – on approach to data representation, OOP programming often simplifies things by providing an agreement on the structure and usage of more abstract entities. For example, an agreement can be made not just on the format of data that should be used to send output to a device such as a printer, but also on the methods of data exchange with that device, including what instructions it understands, and so on. Going back to the racecar analogy, the agreement would include how the engine connects to the fuel tank, how it passes drive power to the wheels, and so on. As the name of the technology suggests, this is achieved using objects .