August 30, 2005

c# Array Append Pattern

Pattern to append one array to the end of another in c#
public static class ArrayAppender
{
  public static TYPE[] Append(this TYPE[] b1, TYPE[] b2)
  {
    TYPE[] newArray = new TYPE[b1.Length + b2.Length];
    Array.Copy(b1, 0, newArray, 0, b1.Length);
    Array.Copy(b2, 0, newArray, b1.Length, b2.Length);
    return newArray;
  }
}

internal class ArrayAppendTester
{
  public void Test()
  {
    int[] intArray1 = new int[4] { 42, 7, 6, 3 };
    int[] intArray2 = new int[7] { 1, 2, 3, 4, 5, 6, 7};

    int[] newArray = ArrayAppender.Append(intArray1, intArray2);
    int[] newArray2 = intArray1.Append(intArray2);
  }
}

Format of an c# Indexer

Indexer format:

class XXX 
{
// RETURN_TYPE is type that is returned by the indexer
// INDEX_TYPE is the indexer look up type
public RETURN_TYPE this[INDEX_TYPE index] 
{
  get{return ...;}
  set{... = value;}
}
Note that their can be multiple indexers
public RETURN_TYPE this[INDEX_TYPE_1 index1, ..., INDEX_TYPE_N indexN] 
{
  get{ ... }
  set{ ... }
}

Equals Operator Pattern

Equality in C#

Pattern for implementing required operators to support '==', '!=', 'Equals()' and 'GetHashCode()' for a new reference or value type. Need to implement these methods together.

For REFERENCE types
public override bool Equals(object rhs)
{
    if (rhs == null) // this cannot be null
        return false;

    if (object.ReferenceEquals(this, rhs)
        return true;

    // Check for null values and compare run-time types.
    if (this.GetType() != rhs.GetType())
         return false;

    return CompareFields(rhs as XXX);
}

private bool CompareFields(XXX p)
{ // Field by field comparison
  return (this.field1 == this.field2) && ...; 
}


public override int GetHashCode()
{   // Aim to get a unique number from the objects state 
    int tmp = ((int)(field1 << 16) + field2) ... ;
    return tmp;
}

In general it is not recommended to override the '==' and '!=' operators for reference types. They should only be overriden for immutable types. However here is a suitable implementation:
public static bool operator ==(XXX obj1, XXX obj2)
{
// IF obj1 is null
//  so obj2 must be for equality
// ELSE obj1 is not null,  
//  compare it with obj2 using above Equals() operator
    if (ReferenceEquals(obj1, null))        
        return ReferenceEquals(obj2, null); 
    else                                    
        return obj1.Equals(obj2);           
}

public static bool operator !=(XXX obj1, XXX obj2)
{
    return !(obj1 == obj2);
}
For VALUE types
public override bool Equals(object rhs)
{
    if (rhs == null) // this cannot be null
        return false;

    return Equals(rhs as XXX);
}

public override bool Equals(XXX rhs)
{
    return CompareFields(rhs);
}


private bool CompareFields(XXX p)
{ // Field by field comparison
  return (this.field1 == this.field2) && ...; 
}

public override int GetHashCode()
{   // Aim to get a unique number from the objects state 
    int tmp = ((int)(field1 << 16) + field2) ... ;

    return tmp;
}

// For VALUE types
public static bool operator ==(XXX lhs, XXX rhs)
{
    bool res = lhs.Equals(rhs);
    return res;
}

public static bool operator !=(XXX lhs, XXX rhs)
{ 
    return !(lhs==rhs); 
}

Here is a Unit Test To Test the Equals operator Create 'x', 'y' and 'z' that are the same and an object 'a' that is not

TestEqualsOperator()
{
  // Ensure all the XXX objects have the same constructor 
  // except the one called 'different'
  XXX a = new XXX(...);
  XXX x = new XXX(...);
  XXX y = new XXX(...);
  XXX z = new XXX(...);
  XXX different = new XXX(...); 

  Debug.Assert(x.Equals(x) == true);
  Debug.Assert(x.Equals(y) == y.Equals(x));
  Debug.Assert((x.Equals(y) && y.Equals(z)) && x.Equals(z));
  Debug.Assert(x.Equals(null) == false);

  Debug.Assert(a.Equals(different) == false);
  Debug.Assert(different.Equals(a) == false);
  Debug.Assert(x.Equals(different) == false);
  Debug.Assert(different.Equals(x) == false);
  Debug.Assert(y.Equals(different) == false);
  Debug.Assert(different.Equals(y) == false);
  Debug.Assert(z.Equals(different) == false);
  Debug.Assert(different.Equals(z) == false);

}

August 18, 2005

My Testing Of DateTime Parsing Capabilities

  
  public static void TestDateTime()
  {
    TestDateParsing(DateTime.Today.ToString());
    TestDateParsing("16/08/2005");
    TestDateParsing("01-08-2005");
    TestDateParsing("25 December 2005");
    TestDateParsing("");
    TestDateParsing("YES");
    /*
Test with: '18/08/2005 00:00:00'
  '18/08/2005'
  Difference in days from today: 0
Test with: '16/08/2005'
  '16/08/2005'
  Difference in days from today: 2
  Date is WITHIN the last '21' days
Test with: '01-08-2005'
  '01/08/2005'
  Difference in days from today: 17
  Date is WITHIN the last '21' days
Test with: '25 December 2005'
  '25/12/2005'
  Difference in days from today: -128
Test with: ''
  Exception caught: 'String was not recognized as a valid DateTime.'
setting dat e to Minimum Value '01/01/0001' Difference in days from today: 732175 Test with: 'YES' Exception caught: 'The string was not recognized as a valid
DateTime. There i s a unknown word starting at index 0.' setting date to Minimum
Value '01/01/0001' Difference in days from today: 732175 */ } public static void TestDateParsing(string str) { DateTime date; try { WL(string.Concat("Test with: \'", str, "\'")); date = DateTime.Parse(str); } catch (Exception ex) { WL(string.Concat(" Exception caught: \'",ex.Message, "\'
setting date to Minimum Value")); date = DateTime.MinValue; } WL(string.Concat(" \'", date.ToString("dd/MM/yyyy"), "\'")); TimeSpan time = DateTime.Now.Subtract(date); WL(string.Concat(" Difference in days from today: ",time.Days)); const int DAYLIMIT = 21; if ((time.Days <= DAYLIMIT) && (time.Days > 0)) { WL(string.Concat(" Date is WITHIN the last \'", DAYLIMIT,
"\' days")); } }
To parse the string "Mon, 08 Apr 2013 09:56:56 +0100" had to use the parse format "ddd, dd MMM yyyy HH':'mm':'ss K"
Like so:
string form = @"ddd, dd MMM yyyy HH':'mm':'ss K";
DateTime.TryParseExact(pubDateNode.Value, form, 
  System.Globalization.CultureInfo.CurrentCulture,
  System.Globalization.DateTimeStyles.AssumeLocal, 
  out when);