Tuesday, October 14, 2008

Checking is a String is a Palindrome


To begin, create a new console application project and add a new method to the Program class as follows.

static bool IsPalindrome(string phrase)
{
}




Convert a String to Title Case

Text can be converted to entirely upper case or lower case using standard methods from the String class. Another common format is title case, where the first letter of each word is usually capitalised. This case can be applied using the TextInfo class.


TextInfo Class

The TextInfo class is used to define the rules within a particular writing system, culture or language. This includes the rules for conversion of a string between cases such as upper, lower and title case. As these rules that are dependent upon the user's local settings or upon a locale specified in code, TextInfo is found in the System.Globalization namespace.

using System.Globalization;

The TextInfo class does not have a public constructor. Instead, an instance of the class must be retrieved from the TextInfo property of a CultureInfo object. An ideal CultureInfo object to use in a Windows Forms application is the user's selected, or current culture. The following command obtains the TextInfo object for the current culture.

TextInfo info = CultureInfo.CurrentCulture.TextInfo;

To perform the conversion to title case, the ToTitleCase method of the TextInfo class is used. The method requires a single parameter containing the string to be formatted. It returns the updated string. In most cases, the new string will have a capital letter for the initial letter of each word and all other letters will be lower case. If a word is already capitalised, this will generally remain as upper case. However, the rules are determined by the selected culture and may differ between languages.

To try the conversion, executed the following:

string sample = "The quick brown fox JUMPS over the lazy dog.";
Console.WriteLine(info.ToTitleCase(sample));

/* Outputs "The Quick Brown Fox JUMPS Over The Lazy Dog."

Adding Methods

Public Methods


public void PressHorn()
{
Console.WriteLine("Toot toot!");
}


To use the new method, change the code within the Main method as follows:

static void Main(string[] args)
{
Vehicle car = new Vehicle();
car.PressHorn(); // Outputs "Toot toot!"
}


Private Methods

To provide for encapsulation, where the internal functionality of the class is hidden, some methods will be defined as private. Methods with a private protection level are completely invisible to external classes. This makes it safe for the code to be modified to change functionality, improve performance, etc. without the need to update classes that use the public interface. To define a method as private, the private keyword can be used as a prefix to the method. Alternatively, using no prefix at all implies that the method is private by default.

The following method of the car class is a part of the internal implementation not the public interface so is defined as being private.

private void MonitorOilTemperature()
{
// Internal oil temperature monitoring code...;
}

To demonstrate that this method is unavailable to external classes, try the following code in the Main method of the program. When you attempt to compile or execute the program, an error occurs indicating that the MonitorOilTemperature method cannot be called due to its protection level.

static void Main(string[] args)
{
Vehicle car = new Vehicle();
car.MonitorOilTemperature();
}

Creating a Simple Class in C#

Creating a Class

The basic syntax for the creation of a new class is very simple. The keyword 'class' followed by the name of the new class is simply added to the program. This is then followed by a code block surrounded by brace characters {} to which the class' code will be added.

class class-name {}


Add a New Class to the Application

Any number of classes may be added to a namespace within a single code file. However, as this would quickly lead to very large files, it is more readable to separate classes into their own files. We will now add a new class file to the project for a class that will describe vehicles.

Choose 'Add Class...' from the Project menu of Visual Studio or Microsoft C# Express Edition. You will be asked for a name for the new class. Type 'Vehicle' and click the Add button. A new class file is generated with the definition of the class already added. Note that the namespace is the same as the namespace in the original file. You can switch between files using the Solution Explorer to compare the namespaces.

Your new class definition should be similar to that below:

namespace ClassTest
{
class Vehicle
{
}
}



Instantiating the Class

Although we have not explicitly added any functionality to the class, it can now be instantiated to create objects. These objects will have the standard behaviour of all classes. To demonstrated this, return to the program code file containing the Main method. In this method we will create a new vehicle object and run its ToString method to see the results. As we have not yet defined how ToString should work, this will simply show the fully qualified name.

static void Main(string[] args)
{
Vehicle car = new Vehicle();
Console.WriteLine(car.ToString()); // Outputs "ClassTest.Vehicle"
}




Generating Random Numbers in c#

The Random Class

Random numbers can be generated with the .NET framework using the Random class. This class represents a pseudo-random number generator that uses a seed state. The class is found in the System namespace.

Generating a Random Integer

The simplest manner in which to use the Random class is for generating random integers. The Next method can be used without parameters to simply return the next integer in the series. The value returned is always a positive integer or zero. Try executing the following code in a console application to generate ten random numbers:

Random r = new Random();

for (int i = 0; i < 10; i++)
{
Console.WriteLine(r.Next());
}

If you run the program several times the random numbers should be different on each occasion. This is because the seed for the random number series is derived from the computer's clock when the Random object is constructed. Unfortunately the system clock has a limited accuracy, leading to the drawback that when several Random objects are created in quick succession they could have the same seed and therefore create the same sequence of pseudo-random numbers.

In the sample code below, three random number generators are instantiated. When you execute the code, you should see that at least two of the objects generate the same number:

Random r1 = new Random();
Random r2 = new Random();
Random r3 = new Random();

Console.WriteLine(r1.Next());
Console.WriteLine(r2.Next());
Console.WriteLine(r3.Next());


Setting a Seed Value

Sometimes the pseudo-random nature of the random number generator can be helpful. If you want to repeat the same sequence of numbers, you can set the seed state during instantiation by passing an integer value to the constructor. The following sample shows this by setting the seed value to one and producing the same sequence several times.

Random r;

for (int i = 0; i < 4; i++)
{
r = new Random(1);

for (int j = 0; j < 4; j++)
{
Console.Write(r.Next()+"\t");
}

Console.WriteLine();
}

Limiting the Range of Random Numbers

Often you will want to limit the size of the range of random numbers that can be generated. In its parameterless version, the values are between zero and 2,147,483,647. To limit the range you can pass an integer to the method. The random number generated will be less than the supplied value.

For example, to generate numbers between zero and ten, you should pass eleven to the parameter, as follows:

Random r = new Random();
Console.WriteLine(r.Next(11));

If you would like to change the lower boundary of the range of numbers that can be generated, you must pass two integers to the Next method. The first parameter specifies the lowest inclusive value in the range. The second parameter is the exclusive upper boundary of the range. Both boundaries may be negative.

To generate a random number between -10 and 10, you could use the following:

Random r = new Random();
Console.WriteLine(r.Next(-10, 11));

Generating Floating Point Random Numbers

If you wish to generate floating-point random numbers, you can use the NextDouble method. This method returns a double-precision floating-point number between zero and one.

Random r = new Random();
Console.WriteLine(r.NextDouble());

Filling a Byte Array with Random Numbers

The last Random method that we will review in this article is the NextBytes method. This method populates an array of bytes with a series of random numbers. The array is declared in advance of the call and passed as a parameter to the method.

Random r = new Random();
byte[] bytes = new byte[256];
r.NextBytes(bytes);

Password setting in c#

If you mean that the password must be exactly 6 characters long and contain at least one uppercase letter, lowercase letter and digit and the other characters (if any) can be anything you like, then try this:

using System;

class Password
{
static void Main()
{
bool lower, upper, digit;
while(true)
{
lower = upper = digit = false;
Console.Write("Enter password : ");
string password = Console.ReadLine();
if (password.Length == 6)
{
foreach(char c in password)
{
if ('a' <= c && c <= 'z')
{
lower = true;
}
else if ('A' <= c && c <= 'Z')
{
upper = true;
}
else if ('0' <= c && c <= '9')
{
digit = true;
}
}
if (lower && upper && digit) break;
}
Console.WriteLine("Invalid, please re-enter");
}
}
}

ASP.NET CODING WITH C#