Introduction
In this article I am going to discuss some important things that might be unknown to most developers. I am going to discuss three topics related to C# and (more helpful) when to build your application.
- Why to use StringBuilder over string to get better performance
- Structure Initialization in C#
- Checked Operator
- Go To with Switch. Case
I will now discuss the list above one by one as follows.
Why to use StringBuilder over string to get better performance
There are no of article and post says that : StringBuilder is more efficient because it does contain a mutable string buffer. .NET Strings are immutable which is the reason why a new string object is created every time we alter it (insert, append, remove, etc.).
In this Section I am going to explain the same thing in more detail to give the beginners more clear view about this fact.
I wrote following code as you can see I have defined one string variable and one StringBuilder variable. Here I am appending string to both type of the variable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace StringTest
{ class Program{static void Main(string[] args) { string s = "Pranay"; s += " rana"; s += " rana1"; s += " rana122"; StringBuilder sb = new StringBuilder(); sb.Append("pranay"); sb.Append(" rana"); } }
}
|
After the execution of above code
s= "pranay rana rana1 rana12"
sb = "pranay rana"
Now to get in more details what happened when append string I use
red-gate.Net Reflector.
Below image shows the IL of the code that I executed above as you can
see
- When I append string its execute
function Concate(str0,str1) to append string.
- When I append string using StringBuilder its call's Append(str)
function.
When I clicked Contact function in reflector it redirect me to the
below code.
As you see Concat function take two argument and return string,
following steps performed when we execute append with string type
- Check for the string is null or not
- Create string dest and allocate memory for the string
- Fill dest string with str0 and str1
- Returns dest string, which is new string variable.
So this proves that whenever i do operation like concatenation of
strings, it creates new strings 'coz of immutable behaviour of strings.
Note:
Above scenario occurs for all the function related to string operation.
When I clicked on Append function in reflector it redirect me to the
below code.
Append function takes one argument of type string and returns
StringBuilder object , following steps performed when we execute append
with StringBuilder type
- Get string value from StringBuilder
object
- Check the its require to allocate memory for the new string we goingto append
- Allocate memory if require and append string
- If not require to allocate memory than append string directly in
existing allocated memory
- Return StringBuilder object which called function by using this
keyword
So it returns same object without creating new one.
Summary
I hope this article help you to understand inner details about the fact
why to use StringBuilder over string to get better performance when you
do heavy/major string manipulations in your code.
Structure Initialization in C#
A structure (struct) in C# allows us to group the variables and methods. It's some what similar to classes but that's not true; there are many difference between class and structure. But here in this article I am not going to discuss about that, here I am going to explain how to Initialize Structure.
Facts:
- Structure is Value type.
- D# doesn't allows to create parameter less constructor because its initialize the variable with the default values.
Now consider the following case where I have created two structures.
structure 1 : with the public members.
public struct StructMember
{
public int a;
public int b;
}
Structure 2 : with the properties.
public struct StructProperties
{
private int a;
private int b;
public int A
{
get
{ return a; }
set
{ a = value; }
}
public int B
{
get
{ return b; }
set
{ b = value; }
}
}
Now by considering the above two facts in mind and I tried to use the both the structure as below.
public class MainClass
{
public static void Main()
{
StructMembers MembersStruct;
StructProperties PropertiesStruct;
MembersStruct.X = 100;
MembersStruct.Y = 200;
PropertiesStruct.X = 100;
PropertiesStruct.Y = 200;
}
}
After doing this when I tried to compile the code I received the following error.
The C# compiler issues the following error:
error CS0165: Use of unassigned local variable 'PropertiesStruct'
So by this the C# compiler says that it allow to use the first structure without an error but not allow to use second structure which exposed property.
To resolve that issue I wrote the following line of code to initialize second structure.
StructProperties PropertiesStruct = new StructProperties();
And after doing this when I compiled code it gets compiled successfully.
To find out the reason why it worked without error when I wrote second line, I reviewed code under dissembler ILDSAM and found that property of the second structure is get implemented as public function in MSIL.
Dissembled code
Fact is struct can be instantiated without using the New operator. If you do not use New, the fields will remain unassigned and the object cannot be used until all the fields are initialized. So this is why we need to use new operator to initialize.
In .Net all simple types are ssStructures so when you write code in C#.
Consider case below where I am creating one integer variable
int a;
Console.WriteLine(a);
than compiler raise an error that you cannot use variable without initializing it.
so you need to write either
default constructor assigned the value 0 to myInt.
int a =0;
or
Using the new operator calls the default constructor of the specific type and assigns the default value to the variable.
int a = new int();
Summary
It's very important to initialize a structure properly when you are coding a structure.
Checked Operator
In the following Section I am going to explain the Checked Operator available in C#.Net to handle the integer overflow.
Problem
In my order management system I have to calculate sales point for the each customer who place order. This sales points are integer values which get earn by customer based on the product they purchase and get deducted from the account as they purchase new product using this points. But there are some customer who are not aware of point system or not consuming this points so that the value of point get increase more than the limit of the integer values i.e. 2^32 . So when ever calculation take place I receive some junk value for those customers who are having point value more than integer value i.e. 2^32.
Solution
To avoid this issue of over flow of integer value and to inform customer who is having more points. I came across a Checked Operator of C#.net.
Checked Operator for Checking for Overflow in Mathematical Operations and conversions for the integer types.
Syntax
Checked( expression )
or
Checked { statements...... }
Example
public static void Main()
{
int a;
int b;
int c;
a = 2000000000;
b = 2000000000;
c = checked(a + b);
System.Console.WriteLine(Int1PlusInt2);
}
When we run above code, it throws exception as below
Exception occurred: System.OverflowException: An exception of type System.OverflowException was thrown.
Which tells that c value is more than the integer type length.
Same way in my application I catch the overflow exception when thrown when calculating the order points and than raise mail to customer that you have to utilise the point you have otherwise you will lose the points after end of xyz period and display point as maxvlaue+ .
Go To with Switch..Case
Go To
Allows us to jump unconditionally when required and it's not recommended to use Go To heavily.
Switch. Case
Statement allows to execute the case block based on the value of the variable or passed in switch i.e. allow to do the condition base programming.
Problem
In my application I reach stage where I have to execute code of the Case 1 of the Switch. Case and if the the some condition satisfy I have to execute the code of Case 3 of Switch. Case.
Example
Switch(myvariable)
{
case 1:
//statements
…........
if ( expression )
execute case 3:
break;
case 2:
…..
break;
case 3:
…......
break;
}
Solution
First solution to this problem is copy the code of case 3 and put it in the if block of case 1
Example
case 1:
//statements
…........
if ( expression )
//code of case 3
break;
But the problem with above solution is it make code redundant.
Second solution is to create function and put the code in that and than execute the code.
case 1:
//statements
…........
if ( expression )
Case3Code();
break;
function Case3Code()
{
….
}
The problem with this solution is that I have to create one Extra function which is no needed.
Third solution is to make use of Go To in switch. case block.
switch(MyVariable)
{
case 1:
//statements
…........
if ( expression )
goto case 3:
break;
case 2:
…..
break;
case 3:
…......
break;
}
So Go to in Switch. Case allow me to do the thing easy and the maintainable way.
Summary
I hope you all enjoyed this feature discuss by me over here, I am going to continue this series which as I get new to add in this list.