Pages

Friday, April 27, 2012


String Builder Class:

Author: Konjerla Suresh

In this Article I want to explain about the string builder class. How it useful when compared with string class

Since C# strings are immutable, an existing string cannot be modified. So, if one tries to change a string either with the concatenation operator (+) or with the Insert, Pad Left, Pad Right, Replace, or Substring methods, an entirely new string is created—leaving the original string intact.

Example:


String1 s1 = “Suresh”;
String2 s2= “Kumar”;
String3 (new String) s3 = s1 + s2;
S3 -> Suresh Kumar.


Therefore, operations which would alter strings—instead—cause additional memory to be allocated. Memory is a scarce resource. And, memory allocations are expensive in terms of memory and performance. Consequently, sometimes String class usage should be avoided.


The StringBuilder class is designed for situations when one needs to work with a single string and make an arbitrary number of iterative changes to it. Many StringBuilder class methods are the same as those of the String class. However, the string content of a StringBuilder class can be changed without the necessity of allocating additional memory. Thus, operations on the StringBuilder class will be much faster than operations on the String class in certain situation



Example:


StringBuilder sb1 = “Suresh”;
StringBuilder sb2 = “Kumar”;
sb1 = sb1 + sb2;
sb1 -> Suresh Kumar



  The String object is immutable while StringBuilder object is mutable. Both String and StringBuilder are reference type. But String acts like a value type.

StringBuilder is located in the System. Text namespace.


Performance Considerations:

A String object concatenation operation always creates a new object from the existing string and the new data. A StringBuilder object maintains a buffer to accommodate the concatenation of new data. New data is appended to the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, and the new data is appended to the new buffer.

The performance of a concatenation operation for a String or StringBuilder object depends on the frequency of memory allocations. A String concatenation operation always allocates memory, whereas a StringBuilder concatenation operation allocates memory only if the StringBuilder object buffer is too small to accommodate the new data. Use the String class if you are concatenating a fixed number of String objects. In that case, the compiler may even combine individual concatenation operations into a single operation. Use a StringBuilder object if you are concatenating an arbitrary number of strings; for example, if you're using a loop to concatenate a random number of strings of user input

Properties:

Name
Description
Capacity
Gets or sets the maximum number of characters that can be contained in the memory allocated by the current instance.
Chars
Gets or sets the character at the specified character position in this instance.
Length
Gets or sets the length of the current StringBuilder object.
MaxCapacity
Gets the maximum capacity of this instance.

Methods:

Method
Description
Append
Appends information to the end of the current StringBuilder.
AppendFormat
Replaces a format specifies passed in a string with formatted text.
Insert
Inserts a string or object into the specified index of the current StringBuilder.
Remove
Removes a specified number of characters from the current StringBuilder.
Replace
Replaces a specified character at a specified index.
ToString
Converts the value of this instance to a String. (Overrides Object.ToString.)
Clear
Removes all characters from the current StringBuilder instance.

Program to explain StringBuilder Class

using
System;
using System. Text;
namespace StringBuilder_example
{
    class Program
    {
        static void Main(string[] args)
        {
            StringBuilder sbstr = new StringBuilder("We are the world");
            Console.WriteLine(sbstr);           
            sbstr.Append (" we are the people");
            Console.WriteLine(sbstr);
            float currency=3400.50f;
            sbstr.AppendFormat(" Our individual salary : {0:C}. ", currency);
            Console.WriteLine(sbstr);
            sbstr.Insert(11, "people of ");
            Console.WriteLine (sbstr);
            sbstr.Remove (11, 10);
            Console.WriteLine (sbstr);
            sbstr.Replace ("world", "Indian");
            Console.WriteLine (sbstr);
            Console.ReadKey ();
        }
    }
}

Output of above program















Thursday, April 26, 2012

Typecasting
Author: Suresh Konjerla
In this article I am going to explain the concept of type casting. Typecasting is concept of converting data from one data type to another data type. C# supports 2 types of type Casting. Those are
1)      Implicit Type Casting
2)      Explicit Type Casting    

C# supports 4 types of Type casting techniques
1)      C++ style of typecasting
2)      Converting
3)      Parsing
4)      Boxing and UnBoxing

Now I am going to explain 1 & 2 types of Type casting techniques here

1)    C++ Style of typecasting :

Syntax:  datatype1 var1 = value;
Datatype2 var2 = (Datatype2) var1;
     Example program:
2)    Converting  :
     Converting is used to type cast data from any data type to another data type.
Working with predefined class called Convert is Converting. Convert Class collection of static methods used for type casting. Those are

è      ToByte(value)     : used to convert data  into Byte data type
è      ToString(value )  : used to convert data into String data type
è      ToBoolean(value): used to convert data into Boolean data type
è      ToChar(value)     : used to convert data into char data type
è      ToInt32(value)    : used to convert data into integer data type
è      To Double(value) : used to convert data into Double data type
          
Example:

    double d = 10.1;
   int x = Convert.ToInt32(d);  // returns 10
   string s = Convert.ToString(d);  //returns 10
   Boolean b = Convert.ToBoolean(d);  //return True
   Byte bt = Convert.ToByte(d); //return 10


Program to convert integer values from 0 to 255 into characters
  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Typecasting1
{
    class ExConverting
    {
        static void Main(string[] args)
        {
            for (int i = 0; i <= 255; i++)
            {
                char c = Convert.ToChar(i);
                Console.Write(c);
                Console.Write(" ");
            }
            Console.ReadKey();
        }
    }
}

Output:

Wednesday, April 25, 2012

Partial Classes

Author: Konjerla Suresh

It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled.

To split a class definition, use the partial keyword modifier,

Using the partial keyword indicates that other parts of the class, struct, or interface can be defined within the namespace. All the parts must use the partial keyword. All of the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as public, private, and so on.

Benefit of partial classes
·                     More than one developer can simultaneously write the code for the class.
·                     You can easily extend VS.NET generated class. This will allow you to write the code of your own need without messing with the system generated code.

Points to be noted while writing code for partial classes
·                     All the partial definitions must proceed with the key word "Partial".
·                     All the partial types meant to be the part of same type must be defined within a same assembly and module.
·                     Method signatures (return type, name of the method, and parameters) must be unique for the aggregated typed (which was defined partially).
·                     The partial types must have the same accessibility.
·                     If any part is sealed, the entire class is sealed.
·                     If any part is abstract, the entire class is abstract.
·                     Inheritance at any partial type applies to the entire class.

Example program:
using System;
using System.Collections.Generic;
using System.Text;

namespace Partial_Class
{
    public partial class Add
    {
        private int x;
        private int y;
        public Add(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }
    public class test
    {
        static void Main(string[] args)
        {
            Add a1 = new Add(10, 15);
            a1.Print();
            Console.ReadKey();
        }
    }
}
Add another .cs file under same project and add the code 
using System;
using System.Collections.Generic;
using System.Text;

namespace Partial_Class
{
    public partial class Add
    {
      public void Print()
      {
        System.Console.WriteLine(" Addition of {0} and {1} is {2}", x, y, x + y);
      }
    }
}
Out put: