Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Friday, September 23, 2011

Remember the old days: The bitwise operations

Take a look at this great article, written by Alessandro Zifiglio, remembering programming basics and something most of the developers forget and unfortunately use too little. In the good old days the bitwise operators were part of our programmer everyday life. Nowadays they are used only by the good developers which still think in optimizations and performance issues.

Bitwise operators in c# OR(|), XOR(^), AND(&), NOT(~)
  
  
  
  

Friday, June 4, 2010

Convert string[] to ArrayList And ArrayList to string[]

This is how you can convert a string[] into an ArrayList in c#
  
  
// string[] -> ArrayList
string[] msg = this.message.Split('\n');

ArrayList arrayList = new ArrayList();
arrayList.AddRange(msg);
  
// ArrayList -> string[]
string[] arrayStrings = arrayList.ToArray(typeof(string)) as string[];

Monday, May 4, 2009

Optimize C# Code... 1

Optimize C# Code... 1

Code optimization is an important aspect of writing an efficient C# application. The following tips will help you increase the speed and efficiency of your C# code and applications.

1. Knowing when to use StringBuilder
You must have heard before that a StringBuilder object is much faster at appending strings together than normal string types.
The thing is StringBuilder is faster mostly with big strings. This means if you have a loop that will add to a single string for many iterations then a StringBuilder class is definitely much faster than a string type.
However if you just want to append something to a string a single time then a StringBuilder class is overkill. A simple string type variable in this case improves on resources use and readability of the C# source code.
Simply choosing correctly between StringBuilder objects and string types you can optimize your code.

2. Comparing Non-Case-Sensitive Strings
In an application sometimes it is necessary to compare two string variables, ignoring the cases. The tempting and traditionally approach is to convert both strings to all lower case or all upper case and then compare them, like such:

str1.ToLower() == str2.ToLower()

However repetitively calling the function ToLower() is a bottleneck in performace. By instead using the built-in string.Compare() function you can increase the speed of your applications.
To check if two strings are equal ignoring case would look like this:

string.Compare(str1, str2, true) == 0 //Ignoring cases

The C# string.Compare function returns an integer that is equal to 0 when the two strings are equal.

3. Use string.Empty
This is not so much a performance improvement as it is a readability improvement, but it still counts as code optimization. Try to replace lines like:

if (str == "")

with:

if (str == string.Empty)

This is simply better programming practice and has no negative impact on performance.
Note, there is a popular practice that checking a string's length to be 0 is faster than comparing it to an empty string. While that might have been true once it is no longer a significant performance improvement. Instead stick with string.Empty.

4. Replace ArrayList with List<>
ArrayList are useful when storing multiple types of objects within the same list. However if you are keeping the same type of variables in one ArrayList, you can gain a performance boost by using List<> objects instead.
Take the following ArrayList:

ArrayList intList = new ArrayList();
intList.add(10);
return (int)intList[0] + 20;

Notice it only contains intergers. Using the List<> class is a lot better. To convert it to a typed List, only the variable types need to be changed:

List intList = new List();
intList.add(10)
return intList[0] + 20;

There is no need to cast types with List<>. The performance increase can be especially significant with primitive data types like integers.

5. Use && and || operators
When building if statements, simply make sure to use the double-and notation (&&) and/or the double-or notation (||), (in Visual Basic they are AndAlso and OrElse).
If statements that use & and | must check every part of the statement and then apply the "and" or "or". On the other hand, && and || go thourgh the statements one at a time and stop as soon as the condition has either been met or not met.
Executing less code is always a performace benefit but it also can avoid run-time errors, consider the following C# code:

if (object1 != null && object1.runMethod())

If object1 is null, with the && operator, object1.runMethod()will not execute. If the && operator is replaced with &, object1.runMethod() will run even if object1 is already known to be null, causing an exception.

6. Smart Try-Catch
Try-Catch statements are meant to catch exceptions that are beyond the programmers control, such as connecting to the web or a device for example. Using a try statement to keep code "simple" instead of using if statements to avoid error-prone calls makes code incredibly slower. Restructure your source code to require less try statements.

7. Replace Divisions
C# is relatively slow when it comes to division operations. One alternative is to replace divisions with a multiplication-shift operation to further optimize C#. The article explains in detail how to make the conversion

From Visual C# Kicks

Thursday, January 29, 2009

.Net Application Single Instance

If you want to ensure that your application only runs one instance at a time, the best method is to use a Mutex.

Mutex: Short for mutual exclusion object. In computer programming, a mutex is a program object that allows multiple program threads to share the same resource, such as file access, but not simultaneously. When a program is started, a mutex is created with a unique name. After this stage, any thread that needs the resource must lock the mutex from other threads while it is using the resource. The mutex is set to unlock when the data is no longer needed or the routine is finished.

On your program.cs unit, do the following:

  
static class Program
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

///
/// The main entry point for the application.
///

[STAThread]
static void Main()
{
bool createdMutex = false;
Process currentProcess = Process.GetCurrentProcess();

Mutex mutex = new System.Threading.Mutex(true,
currentProcess.ProcessName + currentProcess.MachineName + " Mutex", out createdMutex);

if (createdMutex)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());

GC.KeepAlive(mutex);
}
else
{
// Application to topmost window
foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))
{
if (process.Id != currentProcess.Id)
{
SetForegroundWindow(process.MainWindowHandle);
break;
}
}
}
}
}

Wednesday, October 15, 2008

Add any custom controls or Windows Forms controls to a ToolStrip

When we are in need to put some custom controls or Windows Forms controls to a ToolStrip and we think that we only have the options gave to us from the ToolStrip control, we need the help of the ToolStripControlHost Class. This class Hosts custom controls or Windows Forms controls.

Declare a ToolStripControlHost field. In the constructor of the Windows form and after InitializeComponent();, create a new ToolStripControlHost with your required controller in the argument. Then add the ToolStripControlHost to your ToolStrip Items.

It's that easy!!

  
private ToolStripControlHost toolStripControlHost;

public WindowsFormConstructor()
{
InitializeComponent();
toolStripControlHost = new ToolStripControlHost(dateTimePicker1);
toolStrip1.Items.Add(toolStripControlHost);
}

Monday, October 6, 2008

c# ambiguity names between method and event

Maybe some of you have already got to a dead end with ambiguity names, when trying to implement an interface where a method of the interface and an event have the same name, and we won't be able to catch the event triggered by the class.
Ambiguity means that the object of the class doesn't know how to distinguish which to use, because they have the same name, and the compiler will use the method instead of the event.
To get ride of the warning and the error associated with that, given by Visual Studio 2008 "Ambiguity between method and non-method . Using method group.", we need to do some cast inbetween.

The necessary cast will be to the Class of the Interface:
((InterfaceClassName) ourObject).InterfaceEventsName_Event_ EventName += new InterfaceEventsName_EventNameEventHandler(MethodNameToCall);