Saturday, June 28, 2008

Method Parameter Modifiers in C# .NET

All the Methods, both static and instance level, tend to take parameters passed in by the caller. However, unlike some programming languages, C# provides a set of parameter modifiers that control how arguments are sent into (and possibly returned from) a given method, as shown in the Table.

Parameter Modifier

Meaning

(none)

If a parameter is not marked with a parameter modifier, it is assumed to be passed by value, meaning the called method receives a copy of the original data.
out Output parameters are assigned by the method being called (and therefore passed by reference). If the called method fails to assign output parameters, you are issued a compiler error.
params This parameter modifier allows you to send in a variable number of identically typed arguments as a single logical parameter. A method can have only a single params modifier, and it must be the final parameter of the method.
ref The value is initially assigned by the caller, and may be optionally reassigned by the called method (as the data is also passed by reference). No compiler error is generated if the called method fails to assign a ref parameter.

Sunday, June 15, 2008

Best Practices(Class Modifiers in C# .NET)

Every class modifiers has a purpose. One of the best practices is to use appropriate modifiers to meet those purposes.

Abstract

The purpose of making a class abstract is to generalize classes on some common criteria but to prevent from creating instance. Class declared as abstract, it cannot be newed. An abstract class can be derived from another class, it can implement interfaces, and other class can be derived from the abstract class and make the abstract members concrete. If anyone wants to build a class which should not be instantiate but should be sub-classed, the class should be defined as abstract.

Sealed

The purpose of making a class sealed is to prevent inheritance. A sealed class can be derived from another class but cannot be inherited by other classes. If anyone wants to make a class which should not be further subclassed, the class should be declared sealed.


Static

The purpose of making a static class is to prevent both instantiation and inheritance. Usually utiliy classes are made static. static classes are sealed by default. They cannot inherite any class except System.Object and cannot implement any interfaces.

Monday, June 9, 2008

Uses of the Static Keyword in C#.NET(Static Classes)

When a class has been defined as static, it is not creatable using the new keyword, and it can contain only static members or fields (if this is not the case, you receive compiler errors). Static classes are sealed class by default that means a static class cannot be inherited by other class.

This might seem like a very useless feature, given that a class that cannot be created and cannot be inherited does not appear all that helpful. However, if you create a class that contains nothing but static members and/or constant data, the class has no need to be allocated in the first place. Consider the following type:

static class UtilityClass
{
public static void PrintTime()
{ Console.WriteLine(DateTime.Now.ToShortTimeString()); }
public static void PrintDate()
{ Console.WriteLine(DateTime.Today.ToShortDateString()); }
}

Given the static modifier, object users cannot create an instance of UtilityClass:

static void Main(string[] args)
{
UtilityClass.PrintDate();
// Compiler error! Can't create static classes.
UtilityClass u = new UtilityClass();
...
}

Uses of the Static Keyword in C#.NET(Static Constructors)

As you know, constructors are used to set the value of a type's data at the time of construction. If you were to assign the value to a piece of static data within an instance-level constructor, you would be saddened to find that the value is reset each time you create a new object! For example, assume you have updated the SavingsAccount class as so:

class SavingsAccount
{
public double currBalance;
public static double interestRate;
public SavingsAccount(double balance)
{
currBalance = balance;
interestRate = 0.04;
}
...
}

If you execute the previous Main() method, you will see a very different output. Specifically notice how the currInterestRate variable is reset each time you create a new SavingsAccount object.

While you are always free to establish the initial value of static data using the member initialization syntax, what if the value for your static data needed to be obtained from a database or external file? To perform such tasks requires a method scope to author the code statements. For this very reason, C# allows you to define a static constructor:

class SavingsAccount
{
...
// Static constructor.
static SavingsAccount()
{
Console.WriteLine("In static ctor!");
currInterestRate = 0.04;
}
}

Few points of interest regarding static constructors are:

  • A given class (or structure) may define only one single static constructor.
  • A static constructor is executed exactly one time, no matter of how many objects of the type are created.
  • A static constructor does not take an access modifier and cannot take any parameters.
  • The runtime invokes the static constructor when it creates an instance of the class or before accessing the first static member invoked by the caller.
  • The static constructor executes before any instance-level constructors.

Given this modification, when you create new SavingsAccount objects, the value of the static data is preserved, and the output is identical to the output of the Static data program output.

Sunday, June 8, 2008

Uses of the Static Keyword in C#.NET(Static Data)

A type may define static data. When a class defines nonstatic data, each object of this type maintains a private copy of the field. For example, assume a class that models a savings account:
// This class has a single piece of nonstatic data.
class SavingsAccount
{
public double currentBalance;
public SavingsAccount(double balance)
{ currentBalance = balance;}
}

When you create SavingsAccount objects, memory for the currentBalance field is allocated for each instance. Static data, on the other hand, is allocated once and shared among all object instances of the same type. To illustrate the usefulness of static data, add a piece of static data named interestRate to the SavingsAccount class:

class SavingsAccount
{
public double currentBalance;
public static double interestRate = 0.04;
public SavingsAccount(double balance)
{ currentBalance = balance;}
}

If you were to create three instances of SavingsAccount as so:

static void Main(string[] args)
{
// Each SavingsAccount object maintains a copy of the currBalance field.
SavingsAccount s1 = new SavingsAccount(50);
SavingsAccount s2 = new SavingsAccount(100);
SavingsAccount s3 = new SavingsAccount(10000.75);
}

the in-memory data allocation would look something like the figure.

Let's update the SavingsAccount class to define two static methods to get and set the interest rate value. As stated, static methods can operate only on static data. However, a nonstatic method can make use of both static and nonstatic data. This should make sense, given that static data is available to all instances of the type. Given this, let's also add two instance-level methods to interact with the interest rate variable:

class SavingsAccount
{
public double currentBalance;
public static double interestRate = 0.04;
public SavingsAccount(double balance)
{ currentBalance = balance;}
// Static methods to get/set interest rate.
public static SetInterestRate(double newRate)
{ interestRate = newRate;}
public static double GetInterestRate()
{ return interestRate;}
// Instance method to get/set current interest rate.
public void SetInterestRateObj(double newRate)
{ interestRate = newRate;}
public double GetInterestRateObj()
{ return interestRate;}
}

Now, observe the following usage and the output.

static void Main(string[] args)
{
SavingsAccount s1 = new SavingsAccount(50);
SavingsAccount s2 = new SavingsAccount(100);
// Get and set interest rate.
Console.WriteLine("Interest Rate is: {0}", s1.GetInterestRateObj());
s2.SetInterestRateObj(0.08);
// Make new object, this does NOT 'reset' the interest rate.
SavingsAccount s3 = new SavingsAccount(10000.75);
Console.WriteLine("Interest Rate is: {0}", SavingsAccount.GetInterestRate());
Console.ReadLine();
}

Uses of the Static Keyword in C#.NET(Static Methods)

Let us consider a class named Teenager that defines a static method named Complain(), which returns a random string, obtained in part by calling a private helper function named GetRandomNumber():

class Teenager
{
private static Random r = new Random();
private static int GetRandomNumber(short upperLimit)
{ return r.Next(upperLimit); }
public static string Complain()
{
string[] messages = new string[5]{ "Do I have to?",
"He started it!", "I'm too tired...",
"I hate school!", "You are sooo wrong." } ;
return messages[GetRandomNumber(5)];
}
}

Notice that the System.Random member variable and the GetRandomNumber() helper function method have also been declared as static members of the Teenager class.

Like any static member, to call Complain(), prefix the name of the defining class:

// Call the static Complain method of the Teenager class.
static void Main(string[] args)
{
for(int i = 0; i <>
Console.WriteLine("-> {0}", Teenager.Complain());
}

And like any nonstatic method, if the Complain() method was not marked static, you would
need to create an instance of the Teenager class before you could hear about the gripe of the day:

// Nonstatic data must be invoked at the object level.
Teenager joe = new Teenager();
joe.Complain();

Uses of the Static Keyword in C#.NET

In C#, classes, structures and their members may be defined using the static keyword. While doing so, the static member must be invoked directly from the class level, rather than from a type instance. To illustrate the distinction, consider a good friend of ours, the most commonly used System.Console. As you have seen, you do not have to invoke the WriteLine() method from the object level:

// Error! WriteLine() is not an instance level method!
Console c = new Console();
c.WriteLine("I can't be printed...");

but instead simply prefix the type name to the static WriteLine() member:

// Correct! WriteLine() is a static method.
Console.WriteLine("Thanks...");
  • Rule: Static members can operate only on static class members.

If you attempt to make use of nonstatic class members (also called instance data) within a static method, you receive a compiler error.The static keyword can be used before Data, Methods, Constructors and Classes. Lets take a look at them.

(To be continued...)

Saturday, June 7, 2008

Deadlock

Boss said to secretary: For a week we will go abroad, so make arrangement.

Secretary make call to Husband: For a week my boss and I will be going abroad, you look after yourself.

Husband make call to secret lover: My wife is going abroad for a week, so lets spend the week together.

Secret lover make call to small boy whom she is giving private tuition: I have work for a week, so you need not come for class.

Small boy make call to his grandfather: Grandpa, for a week I don't have class 'coz my teacher is busy. Lets spend the week together.

Grandpa(the 1st boss ) make call to his secretary: This week I am spending my time with my grandson. We cannot attend that meeting.

Secretary make call to her husband: This week my boss has some work, we canceled our trip.

Husband make call to secret lover: We cannot spend this week together, my wife has canceled her trip.

Secret lover make call to small boy whom she is giving private tuition: This week we will have class as usual.

Small boy make call to his grandfather: Grandpa, my teacher said this week I have to attend class. Sorry I can't give you company.

Grandpa make call to his secretary: Don't worry this week we will attend that meeting, so make arrangement .

Errors, Bugs, and Exceptions

No programmer is perfect. Writing software is a complex undertaking, and given this complexity, it is quite common for even the best software to be shipped with various problems. Sometimes the problem is caused by "bad code" (such as overflowing the bounds of an array). Other times, a problem is caused by bogus user input that has not been accounted for in the application's code base (e.g., a phone number field assigned "Chucky"). Now, regardless of the cause of said problem, the end result is that your application does not work as expected. To help frame the upcoming discussion of structured exception handling, allow me to provide definitions for three commonly used anomaly-centric terms:

  • Bugs: This is, simply put, an error on the part of the programmer. For example, assume you are programming with unmanaged C++. If you make calls on a NULL pointer or fail to delete allocated memory (resulting in a memory leak), you have a bug.
  • User errors: Unlike bugs, user errors are typically caused by the individual running your application, rather than by those who created it. For example, an end user who enters a malformed string into a text box could very well generate an error if you fail to handle this faulty input in your code base.
  • Exceptions: Exceptions are typically regarded as runtime anomalies that are difficult, if not impossible, to account for while programming your application. Possible exceptions include attempting to connect to a database that no longer exists, opening a corrupted file, or contacting a machine that is currently offline. In each of these cases, the programmer (and end user) has little control over these "exceptional" circumstances.

The Basics of Object Lifetime in C#.NET

While building your C# applications, you can feel free to assume that the managed heap will take care of itself without your direct intervention. In fact, memory management is one of those things which power the .NET platform. The golden rule of .NET memory management is quite simple:Rule: Allocate an object onto the managed heap using the new keyword and forget about it.Once “new-ed”, the garbage collector will destroy the object when it is no longer needed. The next question obviously rises, of course, is, “How does the garbage collector determine when an object is no longer needed?" The incomplete but short answer is that the garbage collector removes an object from theheap when it is unreachable by any part of your code base. Look at the following code, you have a method that allocates a local Car object:

public static void MakeACar()
{
// If myCar is the only reference to the Car object,
// it may be destroyed when the method returns

Car myCar = new Car();
...

}
Notice that the Car reference (myCar) has been created directly within the MakeACar() method and has not been passed outside of the defining scope (via a return value or ref/out parameters). Thus, once this method call completes, the myCar reference is no longer reachable. And this makes the associated Car object a candidate for garbage collection. However, it is not guaranteed that this object will be reclaimed from memory immediately after MakeACar() has completed. All you can assume at this point is that when the CLR(Common Language Runtime) performs the next garbage collection, the myCar object could be(not must be) safely destroyed.As you will most certainly discover, programming in a garbage-collected environment will greatly simplify your application development. In stark contrast, C++ programmers are painfully aware that if they fail to manually delete heap-allocated objects, memory leaks are never far behind. In fact, tracking down memory leaks is one of the most time-consuming (and tedious) aspects of programming with unmanaged languages. By allowing the garbage collector to be in charge of destroying objects, the burden of memory management has been taken from your shoulders and placed onto those of the CLR.