C# Programming Language

Anders Hejlsberg, who co-designed Delphi was brought on board to help with C#. Not surprisingly there are a lot of similarities between the two languages. Both are highly object-oriented with a clear object model and easy to use.  The difference is Delphi’s syntax is based on Pascal while C# is closely related to C++\JAVA. C# requires the .NET runtime to be installed client side. It has several great IDEs and three version of its runtime engine. Mono is a cross platform version of the .NET framework. The .NET framework can be thought of as a competitor to JAVA geared towards MS Windows development. It is a OOP language. For analysis C# can be a powerful tool.  There are many statistical packages available for C# and open source data mining tools such as FANN can be integrated into C#.  Also, for building simulation model, C# is fast, flexible and easy solution as apposed to coding in C++, MatLab or SAS.

Tip 1

Object Everywhere Remember everything is an object in C#, including strings.

string MyStringA = test ; /*lower case*/
string MyStringB = TEST ; /*upper case*/
Console.WriteLine(animal1.CompareTo(MyStringB).ToString()); /*Returns 1*/
Console.WriteLine(animal1.Equals(MyStringB).ToString()); /*Returns 0*/

The code above compares to strings and writes the results of the comparison to the command console. The first compares regardless of case, the second is case sensitive. Notice you execute the CompareTo and Equals functions from the string object you created.

Tip 2

Trap Errors Use error trapping when you want to write you own error handling. Typically, I do this when I want to send an email when a particular error is thrown. After the email is sent I then throw the error. You don’t want to trap errors just to prevent the end users from seeing them or you run the risk of hiding critical and errors.

int i =1;
int j =0;
int k =i/j; /* Divide by zero error.*/
catch (Exception e)
string strError = e.ToString();
Tip 3

Close Connections Always null out dispose of any database connections objects. It is true that in .NET you do not have to directly dispose of .et object.  Like JAVA the garbage collector will eventually clean up unused object however a connection object will remain active until closed in code. This can have disastrous results for the database server and the machine the code is running on as every time the procedure runs another orphaned database connection is created.  You DBA will be running after you with a meet cleaver in no time.

SqlConnection conn = new SqlConnection(sConnectionString);
<< Do you data thing here>>
if (conn != null)
Tip 4

The Switch Statement For readability use switch statements rather than a series of nested if statements to control program s flow.

switch (NyField)
case EventOne :
<<Insert logic here>>
case EventTwo :
<<Insert logic here>>
Tip 5 Cast Effortlessly Here is a quick and easy to cast variable in C#.

intMyVar = (int)sMyVar;
bjMyObject = (objMyObject) objMyObject;
Tip 6

Throw  Exceptions Here is how to throw your own errors in code.  If you trap and error you may want to throw the error after handling the exception.  Sometimes you may want to have a special error defined for your application.

throw new SystemException(“Special Error”);
throw new InvalidCastException();
throw new Exception();
Tip 7

NUnit NUnit is a great testing class that can make running test cases a simple task.

Tip 8 Garbage Collection! C# allows you to do your own garbage collection.  Use this sparingly.  The .NET garbage collection is very good and for the most part you do not need to interfere with it.  But if you do feel the need to tamper with garbage collection:

Tip 9

Create Objects to Store Data Example, storing data in an object. You can use objects to store information in  hastables.  This allows the speed and efficiency of a hastable with structure of an object to store data. 1. First create the class for the obejct

namespace MyTools
public class MyClass
string _strMyField;
string _strInfo;
public string MyField
return this. _strMyField;

this. _strMyField = value;
public DataSummary(string MyParm)
this. _strInfo = MyParm;
2. When poluating a hastable use the obejct as the object value. Hashtable htResults = new Hashtable();
MyTools .MyClass  MyObject = (MyClass  ) MyObject [“My Info”];
htResults.Add(sKey , MyObject);


Cache It At one of my former jobs we had a huge issue with the same query being run hundred of times a day.  Our solution was simple, we had a middle tier written as a C# web service.  To limit the number of times the middle tier queried the database we cached the results of the methods.  The timeout on the catch was set to how often the data a changed.

System.Web.Caching.Cache PLCache;
MyCache = HttpContext.Current.Cache;
if (MyCache[ MyKey ] == null)
Cache.Insert( MyKey ,MyOuput, null, DateTime.Now.AddSeconds(30),TimeSpan.Zero, CacheItemPriority.High,null);
array_out= (ArrayList) MyCache[ MyKey ] ;

Launching a new process. The following could allows you to launch an exe then wait till it is closed.

System.Diagnostics.Process fann = new System.Diagnostics.Process() ;
fann.StartInfo.WorkingDirectory = C:\\”;
fann.StartInfo.FileName = xor_train.exe ;
fann.StartInfo.Arguments= -E ;

StringBuilder If you are concatenating strings in your code instead of using a string object try a StringBuilder object.  StringBuilder objects make better use of memory than strings when the size of the string is dynamic.  If you make heavy use of string concatenation you will see a performance gain from switching.

StringBuilder sbDataKey = new StringBuilder();
sbDataKey.AppendLine(“line one”);
sbDataKey.AppendLine(“line two”);
sbDataKey.AppendLine(“line three”);
string strMyField = sbDataKey.ToString();

Dataset To XML

DS_Main.WriteXml(sFilename, XmlWriteMode.WriteSchema);
MessageBox.Show( Save complete )

XML to Dataset

DS_Main.ReadXml(sFilename, XmlReadMode.ReadSchema);
MessageBox.Show( Dataloaded );

Split A String The method split on a string object allows you to take a string like (1,2,3,4) and generate an array of string values.

string strString = “1,2,3,4”
string[] arrMyArray = strString.Split(new char[] { , });

Very useful when dealing with comma delimitated files.