## C# Controlling Case Sensitivity when comparing two characters

Problem:
You need to compare two characters for equality, but you need the flexibility of performing a cese-sensitive or case-insensitive comarison.

Solution:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class CharEqual
{
public static bool IsCharEqual(char firstChar, char secondChar)
{
return (IsCharEqual(firstChar, secondChar, false));
}
public static bool IsCharEqual(char firstChar, char secondChar, bool caseSensitiveCompare)
{
if (caseSensitiveCompare)
{
return (firstChar.Equals(secondChar));
}
else
{
return (char.ToUpper(firstChar).Equals(char.ToUpper(secondChar)));
}
}
}
class Program
{
static void Main(string[] args)
{
char firstChar = ‘y’;
char secondChar = ‘Y’;

//CharEqual mc = new CharEqual();
if (CharEqual.IsCharEqual(firstChar, secondChar, true))
{
Console.WriteLine("{0} = {1}", firstChar, secondChar);
}
else
{
Console.WriteLine("{0} != {1}", firstChar, secondChar);
}
}
}
}

## C# Fibonaci sequence

Fibonaci Sequence:

Fibonaci sequence is defined that every number is result of addition of two previous numbers in the sequence.
A[n] = A[n – 1] + A[n – 2]
Example: 1, 1, 2, 3, 5….

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i< 51; i++)
{
Console.Write ("{0} ", fibonachi(i));
}
}
static long fibonachi(int n)
{
long Previous = 1;
long prePrevious = 1;
long result = 1;
if (n < 1)
{
return -1;
}
else if (n < 2)
{
return result;
}
for (int i = 2; i < n; i++)
{
result = prePrevious + Previous;
prePrevious = Previous;
Previous = result;
}
return result;
}
}
}

## C#: Resolve a Host Name to an IP Address.

Problem:
You want to determine the IP address for a compter based on its fully qualified domain name by performing a DNS query.

Solution:
In .NET Framework 2.0, use the method GetHostEntry of the System.Net.Dns.Class, and pass the computer’s fully qualified domain name as a string parameter.
(In version 1.0 and 1.1 of the .NET Framework, you should use the method GetHostByName of the DNS class, but it’s marked as obsolete in 2.0.)

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
foreach (string comp in args)
{
try
{
{
}
}
catch (Exception ex)
{
Console.WriteLine("{0} = Error ({1})", comp, ex.Message);
}
}
Console.WriteLine("Press Enter…");
}
}
}

## C#: Effective Class Design

Effective Class Design
1. Type Design
1.1. Nested Types
– When logical grouping and name-collision avoidance are your only goals, namespace should be used.
– Nested types should be used, the notion of member accessibility semantics is a desirable part of you design.

1.2. Class Design
– Do favor using classes over interfaces; Unlike other type systems (e.g., COM) uses interfaces heavily, in the managed world, classes are the most commonly used constructs.
– Best Practice: Always define at least one constructor (and make it private if you don’t want the class creatable).

1.3. Base Class Design
– Recommended to use base class:
– Base class is more versionable; With a class, you can ship V1, and then in V2 decide to add another method.
As long as the method is not abstract (as long as a default implementation is provided), any existing derived classes continue to function unchanged.
Adding a method to an interface is like adding an abstract method to a base class, any class that implements the interface will break.
– Interface is more appropriate in the following scenarios:
– Several unrelated classes want to support the protocol.
– These class already have a base class (no multiple implementation inheritance, but multiple interface inheritance).
– Aggregation is not appropriate or practical.
– For instance, make IByteStream an interface, so a class implement multiple stream types (multiple interface inheritance).
Make ValueEditor as abstract class because dervied class from ValueEditor have no other purpose than to edit value (single implementation inheritance).
– Recommended to provide customization through protected virtual methods:
Customizers of a class often want to implement the fewest methods possible to provide a rich set of functionality to consumers.
To meet this goal, provide a set of non-virtual or final public methods that call through a very small set of protected virtual "Core" methods.
public Control{
public void SetBounds(int x, int y, int width, int height) {
…
SetBoundsCore(…);
}
public void SetBounds(int x, int y, int width, int height, BoundsSpecified specified) {
…
SetBoundsCore(…);
}
protected virtual void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) {
// Do the real work here.
}
}
– Do define a protected constructor on all abstract classes; Many compilers will insert a protected constructor if you do not.
– Avoid prefixing or postfixing "Base", or "Root" as a type is likely to show up in public APIs. Exceptional e.g. ButtonBase class.
– Do prefer using base types in public signatures rather than concrete types to provide better opportunity of substitution and more flexibility in changing the implementation. e.g., public Stream GetDataStream() is prefered to public FileStream GetDataStream().
Do not change inherited public members to private. This does not prevent callers from accessing the base class implemenation.
public class ABaseType {
public void BasePublicMethod() {
Console.WriteLine("Called base implementation.");
}
}
private new void BasePublicMethod() {
Console.WriteLine("Called derived implementation.");
}
}

1.4. Designing for Subclassing
– Do minimize the number and complexity of virtual methods in your APIs. Virtual members defeat some performance optimizations the CLR provides and could "box-in" your design.
– Do think twice before you virtualize members:
– As you version your component (like template methods), you must be sure that the virtual members are called in the same order and frequency.
– GoF: A template method defines an algorithm in terms of abstract operations that subclasses override to provide concrete behavior.
– As you version your virtual members, you must not widen or narrow the inputs and outputs to the members.
– e.g., ArrayList.Item property calls several virtual methods per each MoveNext and Current. Fixing these performance problems could break template methods that are dependent upon virtual method call order and frequency.
Do make only the most complex overload virtual to minimize the number of virtual calls needed to interact with your class and reduce the risk of introducing subtle bugs in subclasses.
Consider sealing virtual members you override from your base class. There are potential bugs with virtual members you introduce in your class as well as virtual members you override.
– Do fully document the contract for any virtual members. It is especially important to specify what guarantees are NOT given about the order in which virtuals are called relative to each other, relative to raising of events, and relative to changes in observable states.

1.5. Interface Design
– Recommended to provide a default implementation of an interface where it is appropriate. E.g., System.Collections.DictionaryBase
class is the default implementation of System.Collections.IDictionary interface.
– Use a marker interface to mark a class and verify the presence of the marker at compile time.
public interface ITextSerializable { } // empty interface
public void Serialize(ITextSerializable item) {
// use reflection to serialize all public properties
…
}
– Use a custom attribute to mark a class (as having a specific characteristic) and verify the presence of the marker at runtime.
[immutable]
public class Key {
…
}
// methods can reject paramters that are not marked with a specific marker at runtime:
public void Add(Key key object value) {
if (!key.GetType().IsDefined(typeof(ImmutableAttribute))) {
throw new ArgumentException("The paramter must be immutable", "key");
}
}
– Consider implementing interface members privately (or explicitly), if the members are intended to be called only through the interface.
– Consider implementing interface members privately (or explicitly) to simulate covariance (to change the type of parameters or return values in "overriden" members).
// Covariance creates strong typed collections.
public class StringCollection : IList {
public String this[int index] { … }
string IList.this[int index] { …}
}
– Do provide protected method that offers the same functionality as the privately implemented mehtod if the functionality is meant to be specialized by dervied classes. Otherwise, it is impossible for inheritors of the type to call the base method(???).
public class List<T> : ISerializable {
void ISerializable.GetObjectData(
SerializationInfo info, StreamingContext context) {
GetObjectData();
}
protected virtual void GetObjectData(
SerializationInfo info, StreamingContext context) {
GetObjectData();
}

1.6. Value Type Design
– Do not define methods on structs that mutate the struct’s state.
NOTE: The pattern for implementing IEnumerable which often involves using a mutable struct (MoveNext() method modifies an internal counter). Although technically this pattern violates this guideline, it is acceptable because the struct is soley for foreach statement, not for users.

1.7. Enum Design
– Do use an Enum to strongly type parameters, properties, and return values.
pulbic enum TypeCode {
Boolean,
Byte,
Char,
DateTiem
…
}
– Do use the System.FlagsAttribute custom attribute for an enum only if a bitwise OR operation is to be performed on the numeric values. Do use powers of two for the enum values so they can easily be combined.
[Flags()]
public enum WatcherChangeTypes {
Created = 1,
Deleted = 2,
Changed = 4,
Renamed = 8,
All = Created | Deleted | Changed | Renamed
}
– Consider providing named constants for commonly used combinations of flags.
[Flags()]
public enum FileAccess {
Write = 2,
}
– Do not use flag enum values that are zero or negative.
[Flags]
public enum SomeFlag
{
ValueA = 0, // bad design, don’t use 0 in flags
ValueB = 1,
ValueC = 2,
ValueBAndC = ValueB | ValueC;
}
SomeFlag flags = GetFlags();
if (flags & SomeFlag.ValueA) // this will never evaluate to true
{
}
– Do argument validation; Do not assume enum arguments will be in the defined range. It is legal to cast any integer value into an enum even if the value is not defined in the enum.
public void PickColor(Color color) {
switch (color) {
case Red: …
case Blue: …
case Green: …
default:
throw new ArgumentOutOfRangeException();
}
// do work
}
NOTE: Do not use Enum.IsDefined() for these checks as it is based on the runtime type of the enum, so thus deceptively expensive and changible out of sync with the code.
public void PickColor(Color color) {
if (!Enum.IsDefined(typeof(Color), color) { // this check is expensive and breakable by versioning
throw new InvalidEnumArgumentException("color", (int)color, typeof(Color));
}
// Security issue: never pass a negative color value
NativeMethods.SetImageColor(color, byte[] image);
}

2. Member Design
2.1. Property Design
– Do allow properties to be set in any order; The semantics are the same regardless of the order in which the developer sets the property values or how the developer gets the object into the active state; Properties should be stateless with respect to other properties.
– Recommended: Components raise <Property>Changed events and there is a protected helper routine On<Property>Changed, which is used to raise the event. Data binding uses this pattern to allow two-way binding of the property.
– Each property that raises <Property>Changed event should provide metadata to indicate that the property supports two-way binding.
Recommended: Components raise <Property>Changing events when the value of a property change via external forces and allow developers to cancel the change by throwing an exception.
class TextBox{
public event TextChangedEventHandler TextChanged;
public event TextChangingEventHandler TextChanging;
public string Text {
get { return text; }
set {
if (text != value) {
OnTextChanging(Event.Empty);
text = value;
OnTextChanged(…);
}
}
}
protected virtual void OnTextChanged(…) { TextChanged(this, …); }
protected virtual void OnTextChanging(…) { TextChanging(this, …); }
}
Avoid throwing exceptions from property getters; If a getter may throw an exception, it should be redesigned to be a method. TIP: One expects exceptions from indexers as a result of validating the index (index bound, type mismatch, etc).

2.2. Properties vs. Methods
– Prefer methods to properties in the following situations:
– The operation is a conversion.
– The operation is expensive, e.g. planning to provide an async version of this operation not to be blocked.
– The operation is not local, e.g. having an observable side effect; different results in succession of calling.
– The member is static but it returns a mutable value.
– The member returns an array, IOW, avoid using array valued properties.
Type type = // get a type window
for (int i = 0; i < type.Methods.Length; i++)
{
if (type.Methods[i].Name.Equals("foo"))
{
…
}
}

* Common Design Considerations
– Have fewer properties and "complex" methods with a large number of parameters to maintain "atomicy" of the actions—Less Customizable.
public class PersonFinder {
public string FindPersonsName (int height, int weight, string hairColor, string eyeColor, int sheoSize, int whichDatabase)
{
// perform operation using the parameters
…
}
}
– Have more properties to set "configuration" (a set of states individually set and hold) and "simple" methods with a small number of parameters.
public class PersonFinder {
public int Height { get {…} set {…} }
public int Weight { get {…} set {…} }
public string HairColor { get {…} set {…} }
public string EyeColor { get {…} set {…} }
public int ShoeSize { get {…} set {…} }
public string FindPersonsName (int whichDatabase)
{
// use the perperties already set to perform operation
}
}

– Do use read-only properties when a user cannot change the logical backing data field.
– Do not use write-only properties; Implement the functionality as a method instead if the property getter cannot be provided.

2.4. Indexed Property (Indexer) Design
– Do use only Int32, Int64, String, and Object for the indexer; If the design requires others for the indexer, strongly re-evaluate if it really represents a logical backing store. If not, use a method.
– Consider using only one index; If the design requires multiple indices reconsider if it really represents a logical backing store. If not, use a method.
– Do use the name Item for indexers unless there is an obiviously better name (e.g. Chars property on String).

2.5. Event Design
– Do use the "raise" terminology for events rather than "fire" or "trigger" terminology. When referring to events in documentation, use the phrase "an event was raised" instead of "an event was fired" or "an event was triggered".
– Do not create a special event handler when not using a strongly typed EventArgs subclass; Simply use the EventHandler class.
– Do use a protected virtual On<Event> method to raise each event in order to provide a way for a derived class to handle the event using an override.
– Do assume that anything can go wrong in an event handler and do not assume that anything about the object state after control returns to the point where the event was raised.
public class Button {
ClickedHandler onClickedHandler;
protected void DoClick() {
PaintDown(); // paint button in depressed state
try {
OnClicked(args); // call event handler
}
finally {
// window may be deleted in event handler
if (windowHandle != null) {
PaintUp(); // paint button in normal state
}
}
}
protected virtual void OnClicked(ClickedEvent e) {
if (onClickedHandler != null)
onClickedHandler(this, e);
}
}
– Do raise cancelable events to allow the caller to cancel events w/o generating an error:
public class MainForm : Form {
TreeView tree = new TreeView();
void LabelEditing(Object source, NodeLabelEditEventArgs e) {
e.Cancel = true;
}
}
– Do raise an exception to cancel an operation and return an exception.
public class MainForm : Form {
TreeView tree = new TreeView();
void TextChanging(Object source, EventArgs e) {
throw new InvalidOperationException("Edit not allowed in this mode");
}
}

2.6. Method Design
– Avoid methods that cannot be called on an object instantiated with a simple constructor because the method requires further initialization of the object. If this is not unavoidable, throw an InvalidOperationException exception clearly stating in the message. e.g., throw new InvalidOperationException("Connection must be valid and open");
– Do use default values correctly in a family of overloaded methods; The complex method should use parameter names that indicate changes from the default states assumed in the simple method.
MethodInfo Type.GetMethod(String name); // case sensitive is assumed.
MethodInfo Type.GetMethod(String name, Boolean ignoreCase); // a change from case sensitive to case insensitive.
– Avoid method families with the simplest overload having more than 3 parameters; Do not have constructor families with the simplest overload having more than 5 parameters.
– If extensibility is needed, do make only the most complete overload virtual and define the other overloads in terms of it.

2.8. Variable Number of Arguments
– Consider using Params if a simple overload could use Params but a complex overload could not and ask yourself "would users value the utility of having params on this overload even if it wouldn’t be on all overloads".
– Do order parameters so that it’s possible to apply "params" to the methods:
e.g., Find (String[], IComparer) would have been written as Find (IComparer, String[]).
– Do not use Params when the array can be modified by the method since the array is temporary and any modifications will be lost.
– Do provide special code paths for a small number of elements in order for performance sensitive code to special case the entire code path. The following pattern is recommended:
void Format (string formatString, object arg1)
void Format (string formatString, object arg1, object arg2)
…
void Format (string formatString, params object[] args)
– CLS requirement: All types that overload operators include alternative methods with appropriate domain-specific names that provide equivalent functionality.
public struct DateTime {
public static TimeSpan operator- (DateTime t1, DateTime t2) { }
public static TimeSpan Substract (DateTime t1, DateTIme t2) { }
}

2.10. Implementing Equals and Operator==

2.11. Conversion Operators
Do not throw exceptions from an implicit cast because it is very difficult for the users to understand what is happening.
– Do case values that are in the same domain; Do not cast values from differnt domains:
e.g., it’s appropriate to convert a Time or TimeSpan into an Int32 where the Int32 still represents the time or duration.
It does not make sense to convert a file name string such as, "c:\mybitmap.gif", into a Bitmap object.

2.12. Constructor Design
– Do have only a default private constructor if there are only static methods and properties on a class.
– Do make static constructors private (called a class constructor or a type initializer).
– Do minimal work in constructors; Constructors should not do much work other than to capture the constructor parameters.
The cost of the other work is delayed until the user uses a particular feature of the instance.
Do not call a virtual method in a constructor if the virtual method is in the constructor’s type.
When a constructor calls a virtual method, there is a chance that the constructor for the instance of the virtual method hasn’t executed.
Annotation: In C++, the vtable is updated during the construction, so that a call to a virtual function during construction only calls to the level of the object hierarchy that has been constructed. For the CLR, the decision is ultimately based on the desire to support extremely fast object creation.
Do throw exceptions from constructors if appropriate. When an exception propagates out of a constructor, the object is created but the operator new does not return the reference. The finalizer of the object will run when the object becomes eligible for collection.
Do use a private constructor, if the type is not meant to be creatable.
The best practice is to always explicitly specify the constructor even if it is a public default constructor.
– Do provide a protected constructor that can be used in derived types.
Recommended: You do not provide a default (parameterless) constructor for a struct (a value type).
Note: Many compilers don’t allow structs to have default parameterless constructors for this reason.
With no constructors, the CLR initializes all the fields of the struct to zero; This is for faster array and static field creation.

* Constructor vs. Static Factory Methods
– Do use static factory if:
– If the parameters to a constructor do not completely describe the object being created, a method name is required to provide more context or more of the semantics of the member.
– If you need to control the instantiation (e.g., in a singleton class), a static factory may return a cached instance to limit the expensive instance creation.
– If you need to return a subclass of the return type, it is often handy to return a subclass to hide implementation details.
public static ArrayList ReadOnly(ArrayList list) {
if (list==null) throw new ArgumentNullException("list");
}
– Do use constructor if:
– If the member needs to be available for subclasses to specialize; Subclasses are not able to customize the behavior of static factory methods.
– if none of the above applies, use constructors as they are more convient than static factories.

2.13. Field Design
– Do not use instance fields that are public or protected; Use a protected property to expose a field to a derived class.
– Do not expose fields to be more versonable:
– Able to change a field to a property while maintaining binary compatibility.
– Able to allow demand-creation or change-notifcation of an object upon usage of the property.
– Do use const (static literal) fields for constants that will NEVER change; compilers burn the values of const fields directly into calling code.
– Do use public static readonly fields for predefined object instance:
public struct Color{
public static readonly Color red = new Color(0x0000FF);
public static readonly Color green = new Color(0x00FF00);
public static readonly Color blue = new Color(0xFF0000);
…
};
– Do not use readonly fileds of mutable types (or arrays).

2.14. Explicit Member Implementation
– Explicit member implementation allows an interface member to be implemented such that it is only available when cast to the interface type.
– Do use explicit members to hide implementation details from public view (or to approximate private interface implementations).
– Do expose an alternative way to access any explicitly implemented members that subclasses are allowed to override.
public class ViolatingBase : ITest
{
void ITest.SomeMethod() { … }
}
public class FixedBase : ITest
{
void ITest.SomeMethod() { SomeMethod(); }
virtual protected void SomeMethod() { … }
}
public class Derived : FixedBased, ITest
{
override protected void SomeMethod()
{
// …
base.SomeMethod();
// This would cause recursion and a stack overflow.
((ITest)this).SomeMethod();
}
}

3.1. Argument Checking
– Perform argument validation for every public or protected method and property set accessor and throw meaningful exceptions to caller. The actual checking could happen at a lower level in some private routines.
class Foo{
public int Count{
get{
return count;
}
set{
if (value < 0 || value >= MaxValue)
throw new ArgumentOutOfRangeException(Sys.GetString("InvalidArgument", "value", value.ToString()));
count = value;
}
}
public void Select(int start, int end){
if (start < 0)
throw new ArgumentException(Sys.GetString("InvalidArgument", "start", start.ToString()));
if (end < start)
throw new ArgumentException(Sys.GetString("InvalidArgument", "end", end.ToString()));
}
}

3.2. Parameter Passing
– In general, favor using enums where it makes the source code more readable; In case where enums would add unneeded complexity and actually hurt readability of the source code, Boolean should be prefered.
– Do use enums if there are two or more Boolean arguments:
FileStream fs = File.Open("foo.txt", true, fale); // No context to understand the meanings of true and false.
FileStream fs = File.Open("foo.txt", CasingOptions.CaseSensitive, FileMode.Open); // Much easier to work with.
Annotation: Most of the time, numerics are passed around as constants and variables (not as "magic numbers"). 80% of the time, a Boolean argument is passed in as a constant to turn a piece of behavior on or off.
Annotation: Developers inadvertently switches two Boolean arguments; It’s somewhat easier to make a mistake even with just one Boolean argument, does true mean "case insensitive" or "case sensitive"?
Annotation: If there is even a slight possibility of needing more options in the future, use an enum now (not to be forced to add another Boolean option).
– Avoid using enums if the method does not take more than one Boolean arguement and there are now and forever only two states.
– If a value is typically set in the constructor, an enum is better; For constructor parameters that map onto properties, a Boolean is better.
Annotation: Today, there is a very small overhead (on the order of 300 bytes for each enum type referenced) but this is at the noise range and should not be considered a factor in choosing to use a Boolean over an enum.

## C#: Design Guide: Disposable Pattern

Design Guide: Disposable Pattern
Both an explicit and an implicit way to free those resources should be provided. Implicit control should always be provided by implementing the protected method Finalize() on an Object (using the destructor syntax in C#). If implemented, the explicit control is provided by a Dispose() method from the IDisposable interface.

public class Window : IDisposable
{
private IntPtr handle; // pointer to a external resource
private Component Components; // other resource you use
private bool disposed = false;
public Window()
{
handle = //allocate on the unmanaged side
otherRes = new OtherResource(…);
}
// Implements IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
//if this is a dispose call dispose on all state you
//hold, and take yourself off the Finalization queue.
if (disposing)
{
Components.Dispose();
}
///free your own state (unmanaged objects)
this.disposed = true;
Component = null;
Release(handle);
handle = IntPtr.Zero;
}
}
//Simply call Dispose(false)
~Window()
{
Dispose (false);
}
//Whenever you do something with this class, check to see if the
//state is disposed, if so, throw this exception.
public void GetWindowHandle()
{
if (this.disposed)
{
throw ObjectDisposedException(…);
}
//…
}
//Derived class
public class MyWindow: Window
{
private bool disposed = false;
public MyWindow()
{
}
protected override void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
//free any disposable resources you own
}
this.disposed = true;
base.Dispose(disposing);
}
}
}
}

– Do make the Finalize() method protected; Do not make it more visible like public.
– Do call base.Finalize method in your finalizer. Note: this is done automatically with the C# and the MC++ destructor syntax.
– Do suppress finalization of your instance once Dispose has been called, unless there is other work to do in Finalize (not covered by Dispose).
– Do call base.Dispose method if it implements IDisposable.
– Consider not being recreatable. Recreating an object that has already been disposed is often a difficult undertaking.
– Do allow your Dispose method to be called more than once w/o throwing an exception. Do nothing after the first call.
– Other instance methods should check whether resources have been disposed. If so, reacquire the resources or throw an ObjectDisposedException.

## C#: Callback Patterns and Choice

Callback Patterns and Choice
Use Event if the following are true:
– One signs up for the callback up front (typically through Add and Remove methods).
– More than one object will typically be cared.
– One is designing a high-level API, esp. a designable Component.

Use Delegate if the following are tru:
– You want a C style function pointer.
– Single callback.
– Registered in a call or at a construction time (not through separate Add method).

Use Interface if the following is true.
– The callback entails complex behavior.

– Do favor using events over methods that take delegates. Events are a more familiar idea to developers, and therefore are simpler to use. Methods taking delegates should only be used when the target user fully understands the concept of delegates, and the situation is not event-related.
Situations such as notification of an object’s state change should be implemented by events only.

Tradeoff: Events are definitely not appropriate as a general purpose customization mechanism. They have much higher performance overhead and as not as flexible as, for example, inheritance based customization.

## C#: Asynchronous Pattern

Asynchronous Pattern

The underlining philosophy is as follows:
– It is the client that decides if a particular call should be asynchronous.
– It is not necessary for a server to do additional programming; The CLI should be able to manage the difference between the client and server views.
– The server can choose to explicitly support asynchronous behavior either because it can implement it more efficiently than a general architecture, or it wants to support only asynchronous behavior.
– It is supposed to enforce type safety.
– The CLI will provide a list of necessary services to support the asynchronous programming model:
– Synchronization primitives, such as critical sections and ReaderWriterLock.
– Synchronization constructs, such as containers that supports WaitForMultipleObjects method.
– Exposure to the underlying infrastructure pieces, such as Message objects and Thread pools.

– The object that implements IAsyncResult must be a waitable object and its underlying synchronization primitive should be signaled after the call is canceled or completed. The waitable objects support waiting to become signaled with "any" or "all" semantics.
– The Cancel method is a request to cancel processing of the method after the desired timeout period has expired and the server is recommended to honor it. The client is recommended to not destory the resources such as file objects as the server may be actively using them. It’s safe for the client to destory the resources after the IsCompleted or IsCancelled property returns true.
– The semantics of the one-way qualifier: The callback itself may execute asynchronously through the context dispatcher infrastructure.
– Calling EndInvoke before the asynchronous operation is complete will block the caller. Calling it a second time with the same AsyncResult is undefined.

class FactorizeCallback {
public FactorizeCallback(unsigned long number) {
_ulNumber = number;
}
// Note the qualifier one-way. See last paragraph of this section for its explanation.
public one-way boolean FactorizedResults(IAsyncResult ar) {
unsigned long factor1, factor2;
FactorizingDelegate fd = ar.AsyncObject;
fd.EndInvoke(factor1, factor2, ar);

// Output the results.
Console.Writeline("Factors of" + _ulNumber + ":" + factor1 + " " + factor2);
}
private unsigned long _ulNumber
}

// Client code.
delegate FactorizingDelegate(unsigned long factorizableNum,
ref unsigned long primefactor1,
ref unsigned long primefactor2);
PrimeFactorizer pf = new PrimeFactorizer();
FactorizingDelegate fd = new FactorizingDelegate(pf.Factorize);

// ———————————————————————————————-
// Async Variation 1.
unsigned long factorizableNum = 1000589023, temp;

// Define the asynccallback delegate.
FactorizeCallback fc = new FactorizeCallback(factorizableNum);
AsyncCallback cb = new AsyncCallback(fc.FactorizedResults);

// Asynchronously invoke the Factorize method on pf.
// Note: If we have pure out parameters, we do not need temp
fd.BeginInvoke(factorizableNum, temp, temp, cb);

// Proceed to do other work.
……

// ———————————————————————————————-
// Async Variation 2.
// Asynchronously invoke the Factorize method on pf.
// Note: If we have pure out parameters, we do not need temp
unsigned long factorizableNum = 1000589023, temp, factor1, factor2;
IAsyncResult ar = fd.BeginInvoke(factorizableNum, temp, temp, NULL);

// Do other work.
……

// Wait for the callback.
SynchronizationServices.WaitForSingleObject(ar);

// Output the results.
fd.EndInvoke(factor1, factor2, ar);
Console.Writeline("Factors of" + factorizableNum + ":" + factor1 + " " + factor2);

Summary
– Supply or DO NOT supply the callback delegate when beginning an asynchronous operation.
– Poll the returned IAsyncResult waitable object for completion.
– End the operation prematurely thereby being blocked until the operation completes.
– Wait on the IAsyncResult waitable object using a timeout to wake up periodically.
– End the operation in the callback routine.

## C#: Static Class Pattern

Static Class Pattern
public sealed class Environment {
private Environment() {}
public static void Exit() {int exitCode) {…}
public static int ExitCode() {
get { … }
set { … }
}
public static String CommandLine() {
get { … }
}
}

NOTICE:
– It is sealed.
– It has a private default constructor.
– It has no instance members.

– Avoid providing static methods that mutate static data—this opens up the possibility for threading bugs.
– Avoid taking locks if possible; Design your library with consideration for the stress of running in a server.
– Be aware that instance state does not always need to be thread-safe, Synchronized() and IsSynchronized() methods.
– Make all static state must be thread-safe—static data is shared across requests.
– Be aware of non-atomic operations—addressing this issue by taking an internal lock tends to be prohibitively expensive.
– Be aware of method calls in locked sections—this will cause a deadlock under heavy threading stress.
– Excessive use of fine-grained synchronization might negatively impact on performance and scalability.
– Consider using System.Threading.Interlocked for simple atomic updates—it’s tempting to use the C# lock statement.
Consider using an interlocked compare exchange to update x only if it is still null.
// Prefer using Interlocked.Increment(myFields);
lock(syncRoot)
{
myFields++;
}
// Prefer using Interlocked.CompareExchange(ref x, rhs(), null));
if (x == null)
{
lock(syncRoot)
{
x = rhs();
}
}
– The best practice is to create an object solely for the purpose of lock.
public Class A {
private Object thisLock = new Object();
lock(thisLock) { … }
}
– lock(this), lock(typeof(MyType), or lock("myLock") is a problem if they are publicly accessible and interned.
– Avoid locking at a too low level; consider having thread- safety to be the caller’s responsibility.
– Consider using a regular lock, Interlocked.Exchange(), or the ReaderWriterLock class.
– Avoid creating architectures that requires developers to deal with threading or concurrency issues;
Wherever possible, try to have the infrastructure handle threading complexities and well documented about sharing scenarios.
– Avoid the need for synchronization if possible—the algorithm can be adjusted to tolerate races rather than eliminating them.

## C# Coding Style Guidelines

Key: A good variable name describes the semantics not the type.

– Prefix private member variables with m_.
public class SomeClass
{
private int m_Number;
}
– With generics, use capital letters for types. Reserve suffixing Type when disabling with the .NET type type.
// Correct
public class LinkedList<K, T> { … }
// Avoid:
public class LinkedList<KeyType, DataType> { … }
– Use delegate inference instead of explicit delegate instantiation.
delegate void SomeDelegate();
public void SomeMethod() { … }
SomeDelegate someDelegate = SomeMethod;
– With anonymous methods mimic the code layout of a regular method, aligned with the anonymous delegate declaration.
a) Comply with placing an open curly brace in a new line.
delegate void SomeDelegate(string someString);
// Correct:
public void InvokeMethod()
{
SomeDelegate someDelegate = delegate(string name)
{
MessageBox.Show(name);
}

someDelegate("Juval");
}
– With empty parenthesis on parameterless anonymous methods.
a) Omit the parenthesis only if the anonymous method could have been used on any delegate.
delegate void SomeDelegate();
// Correct:
SomeDelegate someDelegate = delegate()
{
MessageBox.Show("Hello");
}

// Avoid:
SomeDelegate someDelegate = delegate
{
MessageBox.Show("Hello");
}

– Avoid methods with more than 5 arguments. Use structures for passing multiple arguments.
– Never hardcode a numeric value, always declare a constant instead.
– Use the const directive only on natural constants such as the number of days of week.
Avoid using const on read-only fields. For that, use the readonly directive.
– In a catch statement that throws an exception, always throw the original exception to maintain the stack location of the original error.
When defining custom exceptions, derive the custom exception from ApplicationException and provide custom serialization.
– Avoid friends assemblies, as it increases inter-assembly coupling.
– Assert every assumption, on average, every fifth line is an assertion.
Always explicitly initialize an array of reference types using a for loop.
MyClass[] array = new MyClass[100];
for (int index = 0; index <= array.Length; index++)
{
array[index] = new MyClass();
}
Avoid using the new inheritance qualifier. Use override instead.
Always mark public and protected methods as virtual in a non-sealed class.
Avoid explicit casting. Use the as operator to defensively cast to a type.
– With delegates as class members
a) Copy a delegate to a local variable before publishing to avoid concurrency race condition.
b) Always check a delegate for null before invoking it.
public class MySource
{
public event EventHandler MyEvent;
public void FireEvent();
{
EventHandler temp = MyEvent;
if (temp != null)
{
temp(this, EventArgs.Empty);
}
}
}
– Do no provide public event member variables. Use event accessors instead.
public class MySource
{
MyDelegate m_SomeEvent;
public event MyDelegate SomeEvent;
{
{
m_SomeEvent += value;
}
remove
{
m_SomeEvent -= value;
}
}
}
Use the EventsHelper class defined in Programming .NET Components to publish events defensively.
– Never assume a type supports an interface. Defensively query for that interface.
SomeType obj1;
IMyInterface obj2;
/* Some code to initialize obj1, then: */
obj2 = obj1 as IMyInterface;
if (obj2 != null)
{
obj2.Method();
}
else
{
// Handle error in expected interface
}
– Avoid providing methods on structures.
a) Parameterized constructors are encouraged.
– Do not use late-binding invocation when early-binding is possible.
– Never use goto unless in a switch statement fall-through.
– Always have a default case in a switch statement that asserts.
int number = SomeMethod();
switch(number)
{
case 1:
Trace.WriteLine("Case 1:");
break;
case 2:
Trace.WriteLine("Case 2:");
break;
dfault:
Debug.Assert(false);
break;
}
– Do not use the this reference unless invoking another constructor from within a constructor.
// Example of proper use of ‘this’
public class MyClass
{
public MyClass(string message) { }
public MyClass() : this ("hello") { }
}
– Do not use the base reference to access base class members unless you wish to resolve a conflict with a subclass member of the same name or when invoking a base class constructor.
// Example of proper use of ‘base’
public class Dog
{
public Dog(string name) {}
virtual public void Bark(int howLong) {}
}
public class GermanShepherd : Dog
{
public GermanShepherd(string name) : base(name) {}
override public void Bark(int howLong) { base.Bark(howLong); }
}
– Implement Dispose() and Finalize() methods based on the template in …
– Avoid casting to and from System.Object in code that uses generics. Use constraints or the as operator instead:
// Avoid:
class MyClass<T>
{
void SomeMethod(T t)
{
object temp = t;
SomeClass obj = (SomeClass)temp;
}
}
// Correct:
class MyClass<T> where T : SomeClass
{
void SomeMethod(T t)
{
SomeClass obj = t;
}
}
– Do not define constraints in generic interfaces. Interface level-constraint can be often be replaced by strong-typing.
public interface IList<T> where T : Customer { …  }
public interface ICustomerList : IList<Customer> { … }
– Do not define method-specific containts in interfaces.
– Always prefer using C# generics in data structures.

– Try to initialize local variables as soon as they are declared. For example:
string name = myObject.Name;
or
int val = time.Hours;
– If you initialize a dialog try to use the using statement:
using (OpenFileDialog openFileDialog = new OpenFileDialog()) {
…
}
Note on using Statement: The object you instantiate must implement the System.IDisposable interface.
– A return statement should not use outer most parentheses, e.g., return (n * (n+1) + 2);
– Generally use brackets even if there is only one statement in a loop.
– A logical block of lines should be formatted as a table:
string name    = "Mr. Ed";
int    myValue = 5;
Test   aTest    = Test.TestYou;
– Only use all upper case for identifiers if it consists of an abbreviation which is one or two identifiers of three or more characters should use Pascal Casing instead. For Example:
public class Math
{
public const PI = …
public const Rfc = …
public const feigenBaumNumber = …
}

## C# Programmer’s References

C# Coding / API Design Guidelines for SDE.
Test Code Design Guidelines for SDE/T.

Resources for C# Programmers

## C#: String interning

Code Snippet: String Interning
Recall that the equivalence operator (==) will test for value equivalence for value types and for address or reference equivalence for reference types.

string a = "Hello";     // ldstr
string b = "Hello";     // ldstr (Interning)
string c = String.Copy(a);
Console.WriteLine(a == c);
Console.WriteLine((object)a == (object)c);
Console.WriteLine(a == b);                             // Call the op_Equality method
Console.WriteLine((object)a == (object)b);
// opcode ceq (compare equal)

=== Program Output ===
True
False
True
True

The system is internaling strings—CLI guarantees that the result of two ldstr instructions refering to two metadata tokens with the same sequence of characters return precisely the same string object.

## C# StringBuilder and Splitting Strings

StringBuilder and Splitting Strings

// The StringBuilder Class
StringBuilder sb = StringBuilder("Pineapple");
sb.Replace(‘e’, ‘X’);                        // "PinXapplX"
sb.Insert(4, "Banana");                      // "PinXBananaapplX"
sb.Append("Kiwi");                      // "PinXBananaapplXKiwi"
sb.AppendFormat(", {0}:{1}", 123, 45.6789);  // "PinXBananaapplXKiwi, 123, 45.6789"
sb.Remove(sb.Length – 3, 3);                 // "PinXBananaapplXKiwi, 123, 45.6"
Console.WriteLine(sb.ToString().ToUpper());  // "PINXBANANAAPPLXKIWI, 123, 45.6"

// Splitting Strings
string s = "Once:Upon*A?Time<In>America";
char[] seps = new char[]{’\\’, ‘/’, ‘:’, ‘*’, ‘?’, ‘\"’, ‘|’, ‘<‘, ‘>’};
foreach (string ss in s.Split(seps))
Console.WriteLine(ss);

// Note: Not very useful when trying to split substrings by multiple instances of some character.
string u = "Once___Upon A Time___In America";
char[] sep2 = new char[]{’_‘};
foreach (string ss in u.Split(sep2))
Console.WriteLine(ss);    // "Once", "___", "Upon A Time", "___", "In America"

// Note: Split by one or more occurances of whitespace.
Regex o = new Regex(@"[\s]+");
foreach (string ss in o.Split(u))
Console.WriteLine(ss);   // "Once", "Upon A Time", "In America"

// ProperCase
public static string ProperCase(string s)
{
s = s.ToLower();
string sProper = "";
char [] seps = new char[]{’ ‘};
foreach (string ss in s.Split(seps))
{
sProper += char.ToUpper(ss[0]);
sProper += (ss.Substring(1, ss.Length – 1) + ‘ ‘);
}
return sProper;
}

// IsPalindrome
public static bool IsPalindrome(string s)
{
int iLength, iHalfLen;
iLength = s.Length – 1;
iHalfLen = iLength / 2;
for (int i = 0; i <= iHalfLen; i++)
{
if (s.Substring(i, 1) != s.Substring(iLength – i, 1)
{
return false;
}
}
return true;
}

// Conditional

Question:
Implement a function that reverses a sentence in the following way:  “Hello, my name is Yoshiyuki” ->  “Yoshiyuki is name my ,Hello”.

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
int count;

string msg = "Hello, my ,name .is ,Yoshiyuki Aoyagi.";
Console.WriteLine("OrgMsg: {0} \n", msg);
string[] MsgArray = msg.Split(‘ ‘);
count = MsgArray.Length;
string[] OutMsgArray = new string[count];
int k = 0;
for (int i = count; i > 0; i–)
{
if (MsgArray[i – 1].EndsWith(",") | MsgArray[i – 1].EndsWith("."))
{
int j = MsgArray[i – 1].Length;
string StrTemp = MsgArray[i – 1].Substring(j – 1);
OutMsgArray[k] = StrTemp + MsgArray[i – 1].Remove(j – 1, 1);
}
else
{
OutMsgArray[k] = MsgArray[i – 1];
}
k++;
}
string temp4 = string.Join(" ", OutMsgArray);
Console.WriteLine(temp4);
Console.WriteLine("Press Enter to terminate……");

}
}
}

## C#: Calculate the size of a Directory

Problem:
You need to calculate the size of all files contained  in a directory.

The code:
The DirectoryInfo class does not provide any property that returns size information. However, you can easily calculate the size of all files contained in a directory using the FileInfo.Length property.

using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
return;
}
DirectoryInfo dir = new DirectoryInfo(args[0]);
long DirSize = long.Parse(CalculateDirectorySize(dir, true).ToString());
DirSize = DirSize / 1024;
Console.WriteLine("Total size: " + DirSize + "Kbytes.");
Console.WriteLine(Environment.NewLine);
Console.WriteLine("Main method complete. Press Enter");
}
static long CalculateDirectorySize(DirectoryInfo directory, bool includeSubdirectories)
{
long totalsize = 0;
FileInfo[] files = directory.GetFiles();
foreach (FileInfo file in files)
{
totalsize += file.Length;
}
if (includeSubdirectories)
{
DirectoryInfo[] dirs = directory.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
totalsize += CalculateDirectorySize(dir, true);
}
}