Sunday, April 27, 2008

C# checked and unchecked keywords.

C# arithmetic statements can be executed in checked or unchecked context. "Checked" context checks overflow and raises exception when a arithmetic overflow is detected.

Sample:

short x;
short y;
short z;

x = 10;
y = 20;
z = (short) (x + y);
Debug.Print("\nz = {0}, where x = {1}, y = {2} and z = (short) (x + y);\n", z, x, y);



outputChecked1



x = short.MaxValue;
y = short.MaxValue;
z = (short) (x + y);
Debug.Print("z = {0}, where x = {1}, y = {2} and z = (short) (x + y);\n", z, x, y);


outputChecked2



x = short.MaxValue;
y = short.MaxValue;
try
{
z = checked((short) (x + y));
Debug.Print("z = {0}, where x = {1}, y = {2}\n", z, x, y);
} catch (OverflowException)
{
Debug.Print("OverflowException ==> where x = {1}, y = {2} and z = checked((short) (x + y));\n", z, x, y);
}



outputChecked3



x = short.MaxValue;
y = short.MaxValue;
z = unchecked((short)(x + y));
Debug.Print("z = {0}, where x = {1}, y = {2} and z = unchecked((short)(x + y));\n", z, x, y);


outputChecked4



 



Reference:



checked (C# Reference)



unchecked (C# Reference)



Checked and Unchecked

Thursday, April 24, 2008

CSharp (c#) methods String.PadLeft(), String.PadRight().

    When we need to align output of strings we can use method String.PadLeft() or String.PadRight():

Sample:

string[] initialData = new string[] 
{"one", "two",
"three", "four", "five"};

Console.WriteLine("PadLeft sample");
foreach (string item in initialData)
{
string processedItem = item.PadLeft(10, '.');
Console.WriteLine("'{0}'", processedItem);
}

Console.WriteLine("PadRight sample");
foreach (string item in initialData)
{
string processedItem = item.PadRight(10, '.');
Console.WriteLine("'{0}'", processedItem);
}



Console output:



padConsole



Reference:



String.PadLeft Method



String.PadRight Method

Wednesday, April 23, 2008

CSharp (c#) method String.Join().

When we should create a string, which consists of array of strings with a separator usually we use a iterator (for, foreach).

For example,

string[] stringData = new string[] {"one", "two", "three"};
string outputContent1 = "";
foreach (string item in stringData)
{
outputContent1 += item + ";";
}
outputContent1 = outputContent1.Remove(outputContent1.Length - 1);
Debug.Print("output #1: {0}", outputContent1);



Now, we can use csharp (c#) method String.Join:



string outputContent2 = String.Join(";", stringData);
Debug.Print("output #2: {0}", outputContent2);



Output window:



joinOutput



Reference:



String.Join Method

Thursday, April 17, 2008

Power of Yield, Generics and Array in csharp (C#).

When it is necessary to process a array in normal order, we can use statement foreach.

But if we want to process the array in reverse order: from last array's element to first (0) element, we have a problem. Sure, we can use loop for (in reverse order) or call method Array.Reverse() and reverse elements of original array. Now we can suggest a additional way to get reverse processing of array with help of generics and yield.

Sample: process (output to console) int and string array in "normal" and "reverse" orders:

static void SampleReverese()
{
int[] intArray = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
string[] strArray = new string[] { "zero", "one", "two", "three", "four", "five" };

DisplayArray(intArray);
DisplayArray(Reverse(intArray));
DisplayArray(Reverse(strArray));
}
We can note, methods DisplayArray() and ReverseArray() can receive array of any elements.
It is implemented with help of c# generics.
Method Display():
static void DisplayArray<T>(IEnumerable<T> displayedArray)
{
Console.WriteLine();
foreach (T item in displayedArray)
{
Console.Write("{0} ", item);
}
}
More interesting how to implement method Reverse() without creation of new array or changing original array.
We use statement yield:


static IEnumerable<T> Reverse<T>(T[] originalArray)
{
for (int i = originalArray.Length - 1; i>=0; i--)
{
yield return originalArray[i];
}
}
Console:

reverseConsole

Reference:

yield (C# Reference)

Generics (C# Programming Guide)

Array.Reverse Method (Array)

foreach, in


Wednesday, April 16, 2008

How to remove leading and trailing characters from string in csharp (c#).

To remove leading and trailing characters from string in csharp (c#) we can use methods String.Trim(), String.TrimEnd() or String.TrimStart().

Samples:

originalLine = " message with space, ";
actualLine = originalLine.Trim();
DisplayMessage(originalLine, actualLine);


trimOutput1



originalLine = " message with space, ";
actualLine = originalLine.TrimEnd();
DisplayMessage(originalLine, actualLine);



trimOutput2



originalLine = " message with space, ";
actualLine = originalLine.TrimStart();
DisplayMessage(originalLine, actualLine);



trimOutput3



originalLine = " message with space, ";
actualLine = originalLine.Trim(new char[] { ' ', ',' });
DisplayMessage(originalLine, actualLine);


trimOutput4



Sometimes interesting to see implementation of C# methods.



So, let's see method String.Trim(Char[]):



// Removes a string of characters from the ends of this string. 
public String Trim(params char[] trimChars) {
if (null==trimChars || trimChars.Length == 0) {
trimChars=WhitespaceChars;
}
return TrimHelper(trimChars,TrimBoth);
}


and basic method TrimHelper():



private String TrimHelper(char[] trimChars, int trimType) { 
//end will point to the first non-trimmed character on the right
//start will point to the first non-trimmed character on the Left
int end = this.Length-1;
int start=0;

//Trim specified characters.
if (trimType !=TrimTail) {
for (start=0; start < this.Length; start++) {
int i = 0;
char ch = this[start];
for( i = 0; i < trimChars.Length; i++) {
if( trimChars[i] == ch) break;
}
if( i == trimChars.Length) { // the character is not white space
break;
}
}
}

if (trimType !=TrimHead) {
for (end= Length -1; end >= start; end--) {
int i = 0;
char ch = this[end];
for(i = 0; i < trimChars.Length; i++) {
if( trimChars[i] == ch) break;
}
if( i == trimChars.Length) { // the character is not white space
break;
}
}
}

//Create a new STRINGREF and initialize it from the range determined above.
int len = end -start + 1;
if (len == this.Length) {
// Don't allocate a new string is the trimmed string has not changed.
return this;
}
else {
if( len == 0) {
return String.Empty;
}
return InternalSubString(start, len, false);
}
}





References:



String.Trim Method

Split string to array of strings in csharp (c#).

    When we should divide a string to array of strings by a specific delimiters, we can use method String.Splt().

Samples:

string line = "name,id=1234,,description,user=Jon";



string[] lineItems = line.Split(new char[] { ',' });
DisplayOutput(line, lineItems);


splitOutput1



lineItems = line.Split(new char[] { ',', '=' });
DisplayOutput(line, lineItems);



splitOutput2



lineItems = line.Split(new char[] { ',', '=' }, 2);
DisplayOutput(line, lineItems);


splitOutput3



lineItems = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
DisplayOutput(line, lineItems);



splitOutput4



lineItems = line.Split(new string[] { ",", "id=", "user="}, StringSplitOptions.RemoveEmptyEntries);
DisplayOutput(line, lineItems);



splitOutput5



References:



String.Split Method

Tuesday, April 15, 2008

Utility to check .NET assembly references

Sometimes, when a complex project (many source solutions, dlls, references) is built and run, then we receive a problem with references (here we don't speak about signed assemblies). For example, all dlls has a reference to basic .dll, but a specific .dll has a reference to obsolete version of the basic .dll.

Sample:

MainUtils has a reference to Utils1 (v2.0.0.0) and Utils2 (v2.0.0.0), but Utils2 (v2.0.0.0) has a reference to obsolete version of Utils1 (v1.0.0.0). See folders TestData4References in solution csharp-samples.

referenceDiagram

When a MainUtils will be run, then a error can be shown.

Utility ReferencesManager.exe helps to show all references and output list of all assemblies full names. This information helps to see same assemblies with different versions.

To start the utility it is necessary to type name of initial executable (or .dll) file:

ReferencesManager.exe MainUtils.exe > MainUtils.log

Content of MainUtils.log:

mainUtilsLog

Received log allows to find Utils1 with different versions 1.0.0.0 and 2.0.0.0 and Utils2, which references to Utils1 version 1.0.0.0.

Limitations of version 1.0.1:

  • The utility finds assemblies in GAC and in folder of initial assembly only.
  • The utility doesn't find referenced (in c# source project), but actually not used assemblies.
  • The utility doesn't output list of problematic assemblies.

Downloading ReferencesManager.exe.

References:

Reflector for .NET

Create and Share Flow Charts, Diagrams and More