Friday, April 10, 2009

How to reverse string

   26             string originalString = "123456789";

   27             char[] buffer = originalString.ToCharArray();

   28             Array.Reverse(buffer);

   29             string reversedString = new String(buffer);

   30 

   31             Console.WriteLine();

   32             Console.WriteLine("original string: " + originalString);

   33             Console.WriteLine("reversed string: " + reversedString);

 

image

How to fill String variable.

To fill a string variable, sometimes, they use next way:       const string breakLine = "----------";

Seems, next way (usage one of string’s constructor) will be better:

string line = new string('-', 10);
Console.WriteLine("new string('-', 10) >" + line);

 

Console Output:

image

Thursday, June 5, 2008

Sample of attribute usage in c# (csharp).

        To show usage of attribute let’s write method, which pass all fields of a object and if a field has attribute [NonSerialized], then the method will copy value into the field from second object. The method can be used to restore unserialized fields from original object.

Sample:

Class:

[Serializable]
public class FooClass
{
public int data1;
[NonSerialized] public int data2;
public FooClass(int data1, int data2)
{
this.data1 = data1;
this.data2 = data2;
}
}



Usage:



FooClass destObject = new FooClass(10, 20);
FooClass sourceObject = new FooClass(10, 30);

Debug.Print("destObject.data2: {0}, sourceObject.data2: {1}", destObject.data2, sourceObject.data2);

RestoreUtils.RestoreNonSerialized(destObject, sourceObject);

Debug.Print("destObject.data2: {0}, sourceObject.data2: {1}", destObject.data2, sourceObject.data2);



Output:



output



We can see, that method RestoreUtils.RestoreNonSerialized restored values of destObject field data2 from sourceObject.





Sources of RestoreUtils.RestoreNonSerialized



using System;
using System.Reflection;
using System.Collections;

namespace ReflectionServices
{
public class RestoreUtils
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;

public static void RestoreNonSerialized(object dest, object source)
{
if (dest == null || source == null)
return;

Type objectType = dest.GetType();
if (objectType.IsPrimitive | objectType.IsValueType)
return;

FieldInfo[] dstFieldsInfo = objectType.GetFields(flags);
FieldInfo[] srcFieldsInfo = source.GetType().GetFields(flags);

for (int fieldIndex = 0; fieldIndex < dstFieldsInfo.Length; fieldIndex++)
{
FieldInfo fieldInfo = dstFieldsInfo[fieldIndex];
if (fieldInfo.IsNotSerialized)
{
object newValue = srcFieldsInfo[fieldIndex].GetValue(source);
fieldInfo.SetValue(dest, newValue);
continue;
}

object dstFieldObject = fieldInfo.GetValue(dest);
object srcFieldObject = srcFieldsInfo[fieldIndex].GetValue(source);
if (dstFieldObject != null && srcFieldObject != null)
RestoreNonSerialized(dstFieldObject, srcFieldObject);
}

IEnumerable dstEnumerable = dest as IEnumerable;
if (dstEnumerable != null)
{
IEnumerable srcEnumerable = source as IEnumerable;
if (srcEnumerable != null)
{
IEnumerator srcEnumerator = srcEnumerable.GetEnumerator();
foreach (Object dstItem in dstEnumerable)
{
bool next = srcEnumerator.MoveNext();
if (!next)
break;
Object srcItem = srcEnumerator.Current;

RestoreNonSerialized(dstItem, srcItem);
}
}
}
}
}
}


Reference:



Attributes (C# Programming Guide)



 

How to serialize c# object to binary data.

       The simplest way to serialize object, that is use class BinaryFormatter.

Sample of serialization to file:

using (FileStream stream = new FileStream(tempFilePath, FileMode.Create))
{
BinaryFormatter b = new BinaryFormatter();
b.Serialize(stream, originalData);
}




Sample of deserialization to file:



Data actualData;
using (FileStream stream = new FileStream(tempFilePath, FileMode.Open))
{
BinaryFormatter b = new BinaryFormatter();
actualData = (Data)b.Deserialize(stream);
}


where class Data has attribute [Serializable].



See sources on “C# tips samples” project.



Reference:



BinaryFormatter Class



The simplest way to store object to .xml file in c#.



Monday, May 5, 2008

Comparison of 2 standard c# objects.

    To sort array (or list) of a objects, we need compare 2 objects and define number:

0 - when 2 objects are same;

+1 - when a 1st object more than 2nd;

-1 - when a 1st object less than 2nd.

 

Samples:

Sign of number:

int x;
Console.WriteLine(Environment.NewLine + "int x");
Console.WriteLine("Math.Sign({0}) = {1}", x = 10, Math.Sign(x));
Console.WriteLine("Math.Sign({0}) = {1}", x = -10, Math.Sign(x));
Console.WriteLine("Math.Sign({0}) = {1}", x = 0, Math.Sign(x));


Compare 2 strings:


string s1;
string s2;
bool ignoreCase;
Console.WriteLine();
Console.WriteLine("String.Compare(\"{0}\", \"{1}\") = {2}", s1 = "a", s2 = "b", String.Compare(s1, s2));
Console.WriteLine("String.Compare(\"{0}\", \"{1}\") = {2}", s1 = "b", s2 = "a", String.Compare(s1, s2));
Console.WriteLine("String.Compare(\"{0}\", \"{1}\") = {2}", s1 = "a", s2 = "a", String.Compare(s1, s2));
Console.WriteLine("String.Compare(\"{0}\", \"{1}\") = {2}", s1 = "aa", s2 = "b", String.Compare(s1, s2));
Console.WriteLine("String.Compare(\"{0}\", \"{1}\") = {2}", s1 = "bb", s2 = "a", String.Compare(s1, s2));
Console.WriteLine("String.Compare(\"{0}\", \"{1}\") = {2}", s1 = "A", s2 = "b", String.Compare(s1, s2));
Console.WriteLine("String.Compare(\"{0}\", \"{1}\") = {2}", s1 = "B", s2 = "a", String.Compare(s1, s2));
Console.WriteLine("String.Compare(\"{0}\", \"{1}\", {2}) = {3}", s1 = "a", s2 = "A", ignoreCase = false, String.Compare(s1, s2, ignoreCase));
Console.WriteLine("String.Compare(\"{0}\", \"{1}\", {2}) = {3}", s1 = "a", s2 = "A", ignoreCase = true, String.Compare(s1, s2, ignoreCase));



Compare 2 DateTime objects:


DateTime d1;
DateTime d2;
Console.WriteLine();
Console.WriteLine("DateTime.Compare({0}, {1}) = {2}", d1 = new DateTime(2007, 10, 1), d2 = new DateTime(2007, 10, 1), DateTime.Compare(d1, d2));
Console.WriteLine("DateTime.Compare({0}, {1}) = {2}", d1 = new DateTime(2006, 10, 1), d2 = new DateTime(2007, 10, 1), DateTime.Compare(d1, d2));
Console.WriteLine("DateTime.Compare({0}, {1}) = {2}", d1 = new DateTime(2008, 10, 1), d2 = new DateTime(2007, 10, 1), DateTime.Compare(d1, d2));



Console output:


consoleSign



Reference:



Friday, May 2, 2008

Sorting with help of delegate Comparison.

    When we use Generic class List(T), we can easy to sort it with help of method Sort and delegate Comparison.

Sample.

Definition of class Data:

internal class Data
{
internal int id;
internal string name;
internal Data(int id, string name)
{
this.id = id;
this.name = name;
}
}



Initialization of List<Data>:



List<Data> dataList = new List<Data>();
dataList.Add(new Data(4, "London"));
dataList.Add(new Data(2, "Rome"));
dataList.Add(new Data(3, "New York"));
dataList.Add(new Data(5, "Paris"));
dataList.Add(new Data(1, "Jerusalem"));

DataServices.PrintList("by original order:", dataList);



Sorting dataList by field id:



dataList.Sort(delegate(Data data1, Data data2) { return data1.id - data2.id; });
DataServices.PrintList("by id:", dataList);



Sorting dataList by field name:



dataList.Sort(delegate(Data data1, Data data2) { return String.Compare(data1.name, data2.name); });
DataServices.PrintList("by name:", dataList);



Console output:



consoleComparison



Reference:



List(T).Sort Method



Comparison(T) Generic Delegate



Using IComparable and IComparer to compare objects

Tuesday, April 29, 2008

ReferencesManager 1.0.2 : Utility to check .NET assembly references.

    New build of ReferencesManager (v1.0.2) is released.

    The build include new command line switch:

-path=<customer path>

which allows to define additional folders to search referenced assemblies. For example:

ReferencesManager.exe Main.dll -path=D:\0;D:\1

Downloading ReferencesManager 1.0.2

Sources can be downloaded from "C# tips samples" project.

References:

Utility to check .NET assembly references