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