paste it into your Blogger Template ju

Wednesday 25 February 2015

Generic Methods

In the last post we have seen how to write generic class. Now its the time to move on to generic methods. You can use generic types in methods as well.

Example

using System;
using System.Collections.Generic;

namespace GenericsApplication
{
    class SampleProgram
    {
        static void GenericsSwap(ref T var1, ref T var2)
        {
            T temp;
            temp = var1;
            var1 = var2;
            var2 = temp;
        }
        static void Main(string[] args)
        {
            int a, b;
            char c, d;
            a = 200;
            b = 300;
            c = 'L';
            d = 'M';

            //display values before swap:
            Console.WriteLine("Intiger values before calling swap:");
            Console.WriteLine("a = {0}, b = {1}", a, b);
            Console.WriteLine("Char values before calling swap:");
            Console.WriteLine("c = {0}, d = {1}", c, d);

            //call swap
            GenericsSwap(ref a, ref b);
            GenericsSwap(ref c, ref d);

            //display values after swap:
            Console.WriteLine("Intiger values after calling swap:");
            Console.WriteLine("a = {0}, b = {1}", a, b);
            Console.WriteLine("Char values after calling swap:");
            Console.WriteLine("c = {0}, d = {1}", c, d);
            Console.ReadKey();
        }
    }
}

Output


Int values before calling swap:
a = 200, b = 300
Char values before calling swap:
c = L, d = M
Int values after calling swap:
a = 300, b = 200
Char values after calling swap:
c = M, d = L

Generic Class

Generics allows you to define type-safe datatypes without declaring any datatypes and also you can write methods and class that works in any datatypes. Lets have a look on generics with the below sample code.

Example

using System;
using System.Collections.Generic;

namespace GenericsApplication
{
    public class MyGenericClass<T>
    {
        private T[] array;
        public MyGenericClass(int size)
        {
            array = new T[size + 1];
        }
        public T getItem(int index)
        {
            return array[index];
        }
        public void setItem(int index, T value)
        {
            array[index] = value;
        }
    }
           
    class Sample
    {
        static void Main(string[] args)
        {
            //declaring an int array
            MyGenericClass<int> intArray = new MyGenericClass<int>(5);
            //setting values
            for (int c = 0; c < 5; c++)
            {
                intArray.setItem(c, c*5);
            }
            //retrieving the values
            for (int c = 0; c < 5; c++)
            {
                Console.Write(intArray.getItem(c) + " ");
            }
            Console.WriteLine();
            //declaring a character array
            MyGenericClass<char> charArray = new MyGenericClass<char>(5);
            //setting values
            for (int c = 0; c < 5; c++)
            {
                charArray.setItem(c, (char)(c+97));
            }
            //retrieving the values
            for (int c = 0; c< 5; c++)
            {
                Console.Write(charArray.getItem(c) + " ");
            }
            Console.WriteLine();
            Console.ReadKey();
        }
    }
}

In the above example code you can notice that we have declared a class named MyGenericClass as generic type and in Sample class we are explicitly set the datatype for that class while creating object for it. 

Output
0 5 10 15 20
a b c d e

Sunday 22 February 2015

The Index Of Method in C#

The IndexOf method can be used to check if one character is inside of another. For example, suppose you want to check an email address to see if it contains the @ character. If it doesn't you can tell the user that it's an invalid email address.
Add a new button and a new text box to your form. For the Text property of the text box, enter an email address, complete with @ sign. Double click your button to get at the code. Enter the following:
IndexOf code in C#
The first thing to examine is how IndexOf works. Here's the line of code:
int result = stringEmail.IndexOf( "@" );
The IndexOf method returns an integer. This number is the character's position in the word you're trying to check. In the code above, we want to check the word that's inside of the variable we've called stringEmail. We want to see if it contains the "@" character. This goes between the round brackets of IndexOf. If C# finds the character, it will tell you where it was (at position number 3 in the word , for example). This number is then stored inside of the int variable we've called result. If the character you're looking for can't be found, IndexOf will return a value of -1 (minus 1). The IF statement in our code checks the value of the result variable, to see what's inside of it. If it's -1 display an" Invalid Email Address message"; If it's not -1, a different message is displayed.
Run your programme and click the button. Here's the form with an @ character in the text box:
Check for the @ character in C#
And here's what happens when we delete the @ character from the text box:
The @ character can't be found
Note that the first message box displays "@ found at position 2". If you look at the email address in our text box, however, it's me@me.com. So you might be thinking that the @ character is at position 3, not 2. If C# were to start counting at 1, you'd be right. But it doesn't. When you use the IndexOf method, the count starts at zero.
You can also specify a start position, and a character count for a search. This is useful if you want to do things like checking a longer string and counting how many occurrences there are of a particular character or characters. Or if you want a simple check to see if, say, a website entered in a text box on your form begins with http://www. Here's some code that does just that:
C# code that checks a web address
Have a look at this part of the highlighted line:
webAddress.IndexOf( checkWebAddress, start, numOfChars )
This time, we have three parameters inside of the round brackets of IndexOf. The first one is the string we want to check (checkWebAddress). Then we have start, and numOfChars. The start variable is where in your full string (webAddress) you want to start checking. The third parameter, numOfChars, is the number of characters you want to check from that starting position. In our code, the start is 0 and the number of characters is 10.

And finally, for IndexOf, here's some code that checks a long string of text and counts how many times the word true appears:
The IndexOf Method in C#
The code is a bit complex, so don't worry if you don't understand it all. But it's just using IndexOf with three parameters: the word to search for, a starting position, and how many characters you want to check. The start position changes when the word is found; and the number of characters to count shrinks as you move through the word.

Friday 14 October 2011

Remove and Replace in C#.Net

The Remove Method

As its name suggests, this method is used to Remove characters from a string of text. Here's a simple example of its use:
string oldString = "some text text text";
MessageBox.Show(oldString);
string newString = oldString.Remove(10, 9);
MessageBox.Show(newString);
Remove takes two parameters. The first one is what position in your string you want to start at. (The count starts at zero.) The second parameter is how many characters you want to delete, starting from the position you specified. Add another button to your form and try out the code above.

The Replace Method

The Replace method, you won't be surprised to hear, can be used to replace characters in your string. Here's an example of its use:
string spellingError = "mistak";
spellingError = spellingError.Replace(spellingError, "mistake");
The Replace method takes two parameters, the old word and the new word. In the code above, we're replacing "mistak" with "mistake".

PadLeft and PadRight

The PadLeft and PadRight methods in C# can also be used to insert characters. But these are used to add characters to the beginning and end of your text. As an example, add a new button to your form, and a new text box. For the text box, set the Text property to "Pad Left". Double click your button and enter the following code:
string paddingLeft = textBox5.Text;
paddingLeft = paddingLeft.PadLeft(20);
textBox5.Text = paddingLeft;
The PadLeft and PadRight methods can take 1 or two parameters. We're just using 1. This will insert blank space characters to the start of the string. The total number of characters will be 20. So, if you have four characters in the text box, PadLeft(20) will add 16 blank spaces, making a total of 20 characters in the text box after the button is clicked.
Run your programme and test it out. Type the text "Pad Left" in the text box. Your text box should look like this before the button is clicked:

A Text Box before Pad Left
And it will look like this after you click the button:
A Text Box after Pad Left
If you don't want to pad with blank spaces, you can use the second parameter. This is the character you want to pad with:
paddingLeft = paddingLeft.PadLeft(20 , '*');
In the code above, we're telling C# to pad with the asterisk character, instead of the default blank spaces. (Note the use of the single quotes surrounding the * character. C# doesn't seem to like you using double quotes, if the type is char.)
If you change your code to the one above, then click the button on your form, the result will be this:

Padding with the asterisk character
If you want to add characters to the end of the string, use PadRight instead of PadLeft.

The Insert Method in C#.Net

The Insert method is, not surprisingly, used to insert characters into a string of text. You use it like this:
string someText = "Some Text";
someText = someText.Insert( 5, "More " );
In between the round brackets of Insert, you need two things: A position in your text, and the text you want to insert. A comma separates the two. In our code above, the position that we want to insert the new text is where the T of "Text" currently is. This is the fifth character in the string (the count starts at zero). The text that we want to Insert is the word "More".

Exercise
Test out the code above, for the Insert( ) method. Have one message box to display the old text, and a second message box to display the new text.

The Contains Method in C#.Net

The contains method can be used if you want to check if a string contains certain characters. It's fairly simple to use. Here's an example:
The Contains method in action

After the contains method, you type a pair of round brackets. In between the round brackets, you type the text you're checking for. In our code, we're using an if statement. If it's true that the string contains a "-" character, then some code can be executed.