Thursday, May 30, 2013

String handling in C#

What is string ?
A string is a sequence of characters. In C#, a string is a sequence of unicode characters. It is a data type which stores a sequence of data values, usually bytes, in which elements usually stand for characters according to a character encoding. When a string appears literally in source code, it is known as a string literal.

How to display string ?
It’s very easy to display string in c# . In below code I have given example.
class Program
    {
        static void Main(string[] args)
        {
            string name = "Sourav Kayal";  //Initialization of string
            Console.Write(name);
            Console.Read();
        }
    }
Here name is a string variable and in am initializing string by “=” operator. And I am using string variable name as a argument of Write() function. Like this,
            Console.Write(name);
And the output is here.







 Get length of string.
String class contains Length property , and using that you can get length of string variable. Here below code will show length of string
class Program
    {
        static void Main(string[] args)
        {
            string name = "Sourav";
            Console.Write(name.Length);  // Length property gives length of string
            Console.Read();
        }
    }

And the output is here





Concatenation of  string in c#
It’s very easy to concatenate two and more string in c#. Here ‘+’ operator is overloaded and perform concatenation operation. Here I have given below sample code.
class Program
    {
        static void Main(string[] args)
        {
            string name = "Sourav";
            string surname = " Kayal";
            Console.Write(name + surname);
            Console.Read();
        }
    }
And the output is here.


Convert to uppercase and lowercase.
It’s very natural need to convert lower case string to upper case and vice versa. String class provides toUpper() and toLowe function to get it done. Have a look to below code.
class Program
    {
        static void Main(string[] args)
        {
            string name = "sourav";
            Console.Write(name.ToUpper());  //Make lower case to uppercase

            string SURNAME = "KAYAL";
            Console.Write(SURNAME.ToLower()); //Make upper to lower case

            Console.Read();
        }
    }
This is the output.


Get Sub string from a long string
String class provides SubString() function to get part of string. It takes two argument
1)      Starting character.
2)      Length of character.
Like
Substring(0,3)
Here 0 indicates 0th character means first character. And 3 represent three character from the first character. I have given the code snippet here.

class Program
    {
        static void Main(string[] args)
        {
            string name = "sourav";
            Console.Write(name.Substring(0,3));

            Console.Read();
        }
    }
And the output is


Split long string to string array
If you have a lengthy string separated by some special character, then use split() function to make them separate string each.
Here is the code for them
class Program
    {
        static void Main(string[] args)
        {
            string name = "name1,name2,name3";
            string[] Each_name = name.Split(',');   //Spiliting string by , separator.
            Console.Write(Each_name[1]);
            Console.Read();
        }
    }


And the output is




Wednesday, May 29, 2013

get and set property in C#

What is property ?

We all know C# is a object oriented programming language. And in OOP we are familiar with a great feature called “Encapsulation”. In c# concept of property gives us same flavor . Basically using property we can very easily set and get value of class member. It gives us real time picture of data binding with class object.
Types of property:
Basically property are two types.
Get property:
Using Get property we can get the value of data member of class. The syntax of get property is
get{
                return Membername
      }
Set property
Using set property we can set value of class member .The syntax of set property is
Set
{
Membername=value
}

Example of get and set property

class MyFriend
    {
        private string FriendName;
        private string Street;

        public string P_FirstName
        {
            get{return FriendName;}
            set { FriendName = value; }
        }

        public string P_Street
        {
            get{return Street;}
            set { Street = value; }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyFriend objF = new MyFriend();
            objF.P_FirstName = "Sourav Kayal";   //Setting value in property of FirstName Data member
            objF.P_Street = "Kolkata";           //Setting value in property of Street Data member
            Console.Write("Name:"+ objF.P_FirstName + " Place:" + objF.P_Street); //Geting value of Data Member using property
            Console.ReadLine();
        }
    }


In C# we can  automatically implemented property. This feature indicates to the C# compiler that a hidden field be generated and used as the backing store. Then, the get and set statements are expanded to use that hidden field.

   class MyFriend
    {
        public string FriendName { get; set; }  //Created data member with propertys
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyFriend objF = new MyFriend();
            objF.FriendName = "sourav Kayal";  //Set data member using property
            Console.Write(objF.FriendName);    //Fetching data value using property
            Console.ReadLine();
        }
    }



 Write Validation code using property

We can write validation code within property. In set property before setting value to class member we can implement our business validation logic. Here I have given a example of  business validation using property.

class MyFriend
    {
        private string MobileNumber;
        public string p_MobileNumber
        {
            get {return MobileNumber ; }
            set {
                    if (value.Length < 10)
                        throw new Exception("Please enter 10 digit mobile number");
                    else
                    {
                        MobileNumber = value;
                    }
                }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyFriend objF = new MyFriend();
            try
            {
                objF.p_MobileNumber = "12345";
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }

            Console.ReadLine();
        }
    }




Friday, May 24, 2013

One lession , I have learned from young generation



Face of young generation

Hi guys, Today I will share one of my experience with you. I came out from office a bit early, And fortunately got a bus immediately. The bus was full but not crowded. Just all sits was occupied by passengers.
In next stop(Veidehi hospital stop) , One old person get in and he was just about to stand in front of gate, But i saw one young lady who was sitting just before two row from my sit, has offered her sit to this person. Rely it’s a great behavior(at least in my eye) . I was thinking rely Indian culture is great. How our young generation is . How nice there behavior is . And I was regretting for my cheap mentality. How narrow minded i am ? even for a old person I did not sacrifice my sit?
I have learn a lesion from this young lady. And have taken oath to change my behavior.
My friend , my story did not finish here, please read next paragraph to get complete idea of ladies.
In next stop (TCS stop) a bulk of young stars get in bus(all are software employee). One old person was sitting in my front sit by holding one kid in his lap. And it was ladies sit. Few ladies was already standing in bus. One young lady suddenly demand for that sit . And this old person peacefully leave this sit for this lady ,as it was reserved for them.
I saw this person was standing with difficulty by holding his kid due to jerking. I offered my sit to him .
And for next few minutes I was thinking myself how behavior differ person to person. Where both ladies was from young generation. And one more thing “ Has my mentality is rely change “ . I don’t know how long it will sustain ? .
Any way , thanks to first young lady “ To teach me a lesion”

Thursday, May 23, 2013

Collection in C# with Example


Collection in C#
Collection classes are specialized classes for data storage and retrieval. These classes provide support for
Stacks
 Queues
 Lists
hash tables
Most collection classes implement the same interfaces.
Collection classes serve various purposes, such as allocating memory dynamically to elements and accessing a list of items on the basis of an index etc. These classes create collections of objects of the Object class, which is the base class for all data types in C#.

Stack Class
Stack handles last in first out data processing mechanism. Stack class in one of Collection class of .NET Class library. You have to include using System.Collections.Generic; namespace in order to use collection class in your program.

Create object of collection class like this

            Stack<Int32> st = new Stack<int>();
And you can call push() or pop() method of collection class in order to insert data and delete data symulteniously.

In this below example I have created one object of collection class which is (st). And I have inserted two element in my Stack class. Then I have called st.Pop(); to delete top item of my Stack Collection. Then I am displaying the top most item by calling Peek() function.

Console.Write(st.Peek());
And as I have deleted my top most item from stack now my top item is 100.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BlogProject
{
    class Program
    {
        static void Main(string[] args)
        {

            Stack<Int32> st = new Stack<int>();
            st.Push(100);
            st.Push(200);
            st.Pop();
            Console.Write(st.Peek());
            Console.ReadLine();
        }
    }
}



Queue Class
Queue handles first in first out data processing mechanism. queue class in one of Collection class of .NET Class library. You have to include using System.Collections.Generic; namespace in order to use collection class in your program.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BlogProject
{
    class Program
    {
        static void Main(string[] args)
        {
            Queue<Int32> qu = new Queue<int>();
            qu.Enqueue(100);
            qu.Enqueue(200);
            qu.Dequeue();

            Console.WriteLine(qu.Last());
            Console.ReadLine();

        }
    }
}


Create object of Queue class like this

            Queue<Int32> qu = new Queue<int>();
You can call qu.Enqueue(); function to insert value into your queue.
You can call qu.Dequeue(); function to delete item from your queue. It will delete the first item of the queue what you have inserted.

Now in this program I have inserted two value at first and deleted one item. And by nature the first item(100) will get delete.

And ,then the last tem of my Queue is 200. I can get last item of Queue by calling qu.Last() function.
           





List Class
List class in one of Collection class of .NET Class library. You have to include using System.Collections.Generic; namespace in order to use collection class in your program.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BlogProject
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Int32> lst = new List<int>();
            lst.Add(100);
            lst.Add(200);
            lst.Remove(100);
            Console.WriteLine(lst[0]);
            Console.ReadLine();

        }
    }
}





Create object of List class like this
List<Int32> lst = new List<int>();
To insert data in list object use Add() function. Like below.
lst.Add(100);

To remove particular object from list we have to use Remove() function of List class object. Like

lst.Remove(100);

to get any index value use lst[index]. That is object-name[index]

I have given simple code in below.






Hash Table
HashTable  class is one of Collection class of .NET Class library. You have to include
using System.Collections;
 namespace in order to use collection class in your program.
HashTable use key value pair to store data in Object. In HashTable it’s very easy to search any value as HashTable maintain key to identify specific value.

Here i have given full example of hash table
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace BlogProject
{
    class Program
    {
        static void Main(string[] args)
        {

            Hashtable hashtable = new Hashtable();
            hashtable[1] = "One";
            hashtable[2] = "Two";
            hashtable[13] = "Thirteen";

            foreach (DictionaryEntry entry in hashtable)
            {
                Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
            }

            Console.ReadLine();

        }
    }
}


Here within for each loop I am displaying all value of item using key.