Shiman’s Weblog

Collecting stones from the sea-shore.

C# .NET Method Parameter Modifiers

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.

May 29, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , | No Comments Yet

Best Practices (Class Modifiers in C# .NET)

Every class modifier has specific purposes. 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.

May 29, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , | 1 Comment

Recursion VS Iteration (Looping) : Speed & Memory Comparison

Recursive functions – is a function that partially defined by itself and consists of some simple case with a known answer. Example: Fibonacci number sequence, factorial function, quick sort and more.
Some of the algorithms/functions can be represented in iterative way and some may not.

Iterative functions – are loop based imperative repetition of a process (in contrast to recursion which has more declarative approach).

Comparison between Iterative and Recursive approaches from performance considerations

Factorial:

//recursive function calculates n!
static int FactorialRecursive(int n)
{
if (n <= 1) return 1;
return n * FactorialRecursive(n - 1);
}
//iterative function calculates n!
static int FactorialIterative(int n)
{
int sum = 1;
if (n <= 1) 
return sum;
while (n > 1)
{
sum *= n; n--;
}
return sum;
}

N

Recursive

Iterative

10

334 ticks

11 ticks

100

846 ticks

23 ticks

1000

3368 ticks

110 ticks

10000

9990 ticks

975 ticks

100000

stack overflow

9767 ticks

As we can clearly see the recursive is a lot slower than the iterative (considerably) and limiting (stackoverflow).

The reason for the poor performance is heavy push-pop of the registers in the ill level of each recursive call.

Fibonacci:

//--------------- iterative version --------------------- 
static int FibonacciIterative(int n)
{
if (n == 0) 
return 0;
if (n == 1) 
return 1;
int prevPrev = 0;
int prev = 1;
int result = 0;
for (int i = 2; i <= n; i++)
{
result = prev + prevPrev;
prevPrev = prev;
prev = result;
}
return result;
}
//--------------- naive recursive version --------------------- 
static int FibonacciRecursive(int n)
{
if (n == 0) 
return 0;
if (n == 1) 
return 1;
return FibonacciRecursive(n - 1) + FibonacciRecursive(n - 2);
}
//--------------- optimized recursive version ---------------------
static Dictionary resultHistory = new Dictionary();
static int FibonacciRecursiveOpt(int n)
{
if (n == 0) 
return 0;
if (n == 1) 
return 1;
if (resultHistory.ContainsKey(n)) 
return resultHistory[n];
int result = FibonacciRecursiveOpt(n - 1) + FibonacciRecursiveOpt(n - 2);
resultHistory[n] = result;
return result;
}

N

Recursive

Recursive opt.

Iterative

5

5 ticks

22 ticks

9 ticks

10

36 ticks

49 ticks

10 ticks

20

2315 ticks

61 ticks

10 ticks

30

180254 ticks

65 ticks

10 ticks

100

too long/stack overflow

158 ticks

11 ticks

1000

too long/stack overflow

1470 ticks

27 ticks

10000

too long/stack overflow

13873 ticks

190 ticks

100000

too long/stack overflow

too long/stack overflow

3952 ticks

As before the recursive approach is worse than iterative however, we could apply memoization pattern (saving previous results in dictionary for quick key based access), although this pattern isn’t match for iterative approach (but definitely improvement over the simple recursion).

Now let’s think about when it is a good idea to use recursion and why. In many cases there will be a choice: many methods can be written either with or without using recursion.

    Q: Is the recursive version usually faster?
    A: No — it’s usually slower (due to the overhead of maintaining the stack)
    Q: Does the recursive version usually use less memory?
    A: No — it usually uses more memory (for the stack).
    Q: Then why use recursion??
    A: It makes the code beautiful – recursion is a beauty of programming. Sometimes it is much simpler to write the recursive version.

May 28, 2008 Posted by shiman | Algorithm, Computer Science, Programming | , , , | 10 Comments

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.

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 void 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();
}

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 < 10; 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();

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.

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();
    //...
}

May 27, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , , , , , , | 1 Comment

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 .

May 27, 2008 Posted by shiman | Computer Science, Jokes | , , | 4 Comments

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.

May 14, 2008 Posted by shiman | Computer Science, Programming | , , | No Comments Yet

The Basics of Object Lifetime in C#.NET

May 13, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , | 2 Comments

Differences between an Abstract Class and an Interface

An Abstract class without any implementation just looks like an Interface, so what is the significance of using Interfaces instead of an Abstract classes?

This Post is now moved to:

http://darkcodingzone.blogspot.com/2008/11/differences-between-abstract-class-and.html

May 12, 2008 Posted by shiman | Computer Science, OOP, Programming | , , , , , | No Comments Yet