Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Thursday, November 20, 2008

C# .NET Method Parameter Modifiers (The out Modifier)

In a previous post I told about 4 method parameter modifiers of C#. The out modifier is one of them. In this post, I am going to tell about it and its purpose.

Methods that have been defined to take output parameters are under obligation to assign them to an appropriate value before exiting the method in question (if you fail to ensure this, you will receive compiler errors).

To illustrate, consider the Add() method that returns the sum of two integers using the C# out modifier (note the physical return value of this method is now void):

// Output parameters are allocated by the member.
public static void Add(int x, int y, out int ans)
{
ans = x + y;
}

Calling a method with output parameters also requires the use of the out modifier. Local variables passed as output variables are not required to be assigned before use (if you do so, the original value is lost after the call), for example:

static void Main(string[] args)
{// No need to assign local output variables.
int ans;Add(90, 90, out ans);
Console.WriteLine("90 + 90 = {0} ", ans);
}

The previous example is intended to be illustrative in nature; you really have no reason to return the value of your summation using an output parameter. However, the C# out modifier does serve a very useful purpose: it allows the caller to obtain multiple return values from a single method invocation.

// Returning multiple output parameters.
public static void FillTheseValues(out int a, out string b, out bool c)
{
a = 9; b = "Enjoy your string."; c = true;
}

The caller would be able to invoke the following method:

static void Main(string[] args)
{
int i;
string str;
bool b;
FillTheseValues(out i, out str, out b);
Console.WriteLine("Int is: {0}", i);
Console.WriteLine("String is: {0}", str);
Console.WriteLine("Boolean is: {0}", b);
}

Wednesday, November 19, 2008

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.

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

Tuesday, November 18, 2008

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.

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

Monday, November 17, 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:

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

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...)

Sunday, November 16, 2008

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.

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?

The concepts of Abstract classes and Interfaces are always confusing to the beginners of OOP, though they have been through all the theories. Therefore, in this post, I have tried to discuss these two things.

An Abstract class is a special kind of class that cannot be instantiated. It only allows other classes to inherit from it but cannot be instantiated. When we create an abstract class, we are creating a base class that might have one or more completed methods but some methods can be left uncompleted.

An Interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body.

An interface is similar to an abstract class. Both types must be inherited. You cannot create an instance of either. Abstract members require implementation in the derived type. Interface members require implementation in a derived type. Although abstract and interface members are similar, there are several differences:

  • An abstract class can contain some implementation. Interfaces have no implementation.

  • Abstract classes can inherit other classes and interfaces. Interfaces can only inherit other interfaces.

  • Abstract classes can contain fields. Interfaces cannot have state.

  • Abstract classes have constructors and destructors. Interfaces have neither.

  • Interfaces can be inherited by structures. Abstract classes are not inheritable by structures.

  • Interfaces support multiple inheritance. Abstract classes support single inheritance.

If all the methods of an abstract class are uncompleted then it is same as an interface. And everyone knows that an abstract class can provide some defoult behaviors to the sub-classes which an Interface cannot. But if we can have a complete abstract class (which looks like an Interface), then why the heck do we need Interfaces?

The answer is, most of the Object Oriented Languages do not support multiple inheritance. But, it is obvious that sometimes we need a class to have behavior like more than one class, and the language is not supporting that- we cannot extend more than one class. So, to provide this feature of multiple inheritance, we need interfaces, because it is possible for a class to implement multiple interfaces.