30.10.08

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:
  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • 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.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

Sample Code

public class Bus
{
// Static constructor:
static Bus()
{
System.Console.WriteLine("The static constructor invoked.");
}
public static void Drive()
{
System.Console.WriteLine("The Drive method invoked.");
}
}
class TestBus
{
static void Main()
{
Bus.Drive();
}
}

Sample Try - Catch in SQL 2005

begin tran Tran_DeleteAll
begin try
--Sample code
end try

begin catch
set @EMessage = @ProcedureName + ':' + ERROR_MESSAGE()
execute dbo.SPname @arg1,@arg2, 1, NULL, NULL, 2
rollback tran Tran_DeleteAll
end catch

Static Classes and Static Class Members

Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static classes can be used when there is no data or behavior in the class that depends on object identity.
  • Static Classes

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
The main features of a static class are:

Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state.

Sample Code

static class CompanyInfo
{
public static string GetCompanyName() { return "CompanyName"; }
public static string GetCompanyAddress() { return "CompanyAddress"; }
}

  • Static Members

A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are often used to represent data or calculations that do not change in response to object state; for instance, a math library might contain static methods for calculating sine and cosine.

Sample code

public class Automobile
{
public static int NumberOfWheels = 4;
public static int SizeOfGasTank
{
get
{
return 15;
}
}
public static void Drive() { }
public static event EventType RunOutOfGas;
}
Static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member. For example:

Automobile.Drive();
int i = Automobile.NumberOfWheels;

Sample code

public static class TemperatureConverter
{
public static double CelsiusToFahrenheit(string temperatureCelsius)
{
// Convert argument to double for calculations.
double celsius = System.Double.Parse(temperatureCelsius);
// Convert Celsius to Fahrenheit.
double fahrenheit = (celsius * 9 / 5) + 32;
return fahrenheit;
}
public static double FahrenheitToCelsius(string temperatureFahrenheit)
{
// Convert argument to double for calculations.
double fahrenheit = System.Double.Parse(temperatureFahrenheit);
// Convert Fahrenheit to Celsius.
double celsius = (fahrenheit - 32) * 5 / 9;
return celsius;
}
}
class TestTemperatureConverter
{
static void Main()
{
System.Console.WriteLine("Please select the convertor direction");
System.Console.WriteLine("1. From Celsius to Fahrenheit.");
System.Console.WriteLine("2. From Fahrenheit to Celsius.");
System.Console.Write(":");
string selection = System.Console.ReadLine();
double F, C = 0;
switch (selection)
{
case "1":
System.Console.Write("Please enter the Celsius temperature: ");
F = TemperatureConverter.CelsiusToFahrenheit(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
break;
case "2":
System.Console.Write("Please enter the Fahrenheit temperature: ");
C = TemperatureConverter.FahrenheitToCelsius(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Celsius: {0:F2}", C);
break;
default:
System.Console.WriteLine("Please select a convertor.");
break;
}
}
}


7.10.08

Property in C#:

Property ? it is a special method that can return a current object?s state or set it. Simple syntax of properties can see in the following example:
public int Old
{
get {return m_old;}
set {m_old = value;}
}
public string Name
{
get {return m_name;}
}
Here are two types of properties. A first one can set or get field of class named m_old, and the second is read only. That?s mean it can only get current object?s state.
The significance of these properties is its usability. These properties need not be called with any function names like objectname.get or objectname.set etc., But they can be directly assigned the values or retrieve the values.
Static Properties
C# also supports static properties, which belongs to the class rather than to the objects of the class. All the rules applicable to a static member are applicable to static properties also.
The following program shows a class with a static property.
using System;
class MyClass
{
private static int x;
public static int X
{
get{return x;}
set{x = value;}
}
}
class MyClient
{
public static void Main()
{
MyClass.X = 10;
int xVal = MyClass.X;
Console.WriteLine(xVal);//Displays 10
}
}
Remember that set/get accessor of static property can access only other static members of the class. Also static properties are invoking by using the class name.
Properties & Inheritance
The properties of a Base class can be inherited to a Derived class.
using System;
class Base
{
public int X
{
get
{
Console.Write("Base GET");
return 10;
}
set
{Console.Write("Base SET");}
}
}
class Derived : Base{}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.X = 10;
Console.WriteLine(d1.X);//Displays 'Base SET Base GET 10'
}
}
The above program is very straightforward. The inheritance of properties is just like inheritance any other member.
Properties & Polymorphism
A Base class property can be polymorphicaly overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level.
using System;
class Base
{
public virtual int X
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}
class Derived : Base
{
public override int X
{
get
{
Console.Write("Derived GET");
return 10;
}
set
{
Console.Write("Derived SET");
}
}
}
class MyClient
{
public static void Main()
{
Base b1 = new Derived();
b1.X = 10;
Console.WriteLine(b1.X);//Displays 'Derived SET Derived GET 10'
}
}
Abstract Properties
A property inside a class can be declared as abstract by using the keyword abstract. Remember that an abstract property in a class carries no code at all. The get/set accessors are simply represented with a semicolon. In the derived class we must implement both set and get assessors.
If the abstract class contains only set accessor, we can implement only set in the derived class.
The following program shows an abstract property in action.
using System;
abstract class Abstract
{
public abstract int X
{
get;
set;
}
}
class Concrete : Abstract
{
public override int X
{
get
{
Console.Write(" GET");
return 10;
}
set
{
Console.Write(" SET");
}
}
}
class MyClient
{
public static void Main()
{
Concrete c1 = new Concrete();
c1.X = 10;
Console.WriteLine(c1.X);//Displays 'SET GET 10'
}
}
The properties are an important features added in language level inside C#. They are very useful in GUI programming. Remember that the compiler actually generates the appropriate getter and setter methods when it parses the C# property syntax.

Output Parameters in Methods:

The return values in any function will be enough for any one if only one value is needed. But in case a function is required to return more than one value, then output parameters are the norm. This is not supported in C++ though it can be achieved by using some programming tricks. In C# the output parameter is declared with the keyword out before the data type. A typical example is as follows.

public void CalculateBirthYear(ref int year, out int birthyear)
{
int b = year - m_old;
Console.WriteLine("Birth year is {0}",b);
birthyear = b;
return;
}

Strictly speaking there is no difference between ref and out parameters.
The only difference is that the ref input parameters need an input value and the out parameters dont. Ref parameter Should be initilized before call. Out need not to initilized before call.
Ref paramenter is nothing but in & out parameter.
Out is only out parameter.
There is no performance issue occured.
A ref or out argument must be an lvalue.ie, you need to pass the same signature.
The casting is not allowed for both when you pass thevalues to ref/out.