vineri, 29 ianuarie 2010

Abstract Factory Pattern

Abstract Factory Pattern

Abstract Factory Pattern


  • An abstract factory provides an interface for creating families of related objects without specifying their concrete classes.
  • Could be seen as a hierarchy that support multiple environment and produce different suites of products
  • It avoids duplicating the decision making everywhere an instance is created.
  • It is useful for generating different layouts and multiple-look-and-feel user interfaces.

Concrete sample of use for Abstract Factory



HandBags Factory




EuropeFactory, AfricaFactory

GenuineBag Factory, FakeBag Factory

Cassete Device, CD Device, DVD Device

RealTimeViewFactory, ReplayViewFactory


Herbivore, Carnivore

HandBagOne, HandBabTwo

Audio Quality, Video Quality

Grid View, Chart View, CSV only View


Deer, Beer, Zebra, Lion

BagTypeOneGenuine, BagTypeTwoGenuine,

BagTypeOneFake, BagTypeTwofake

Cassette Audio Quality, CD Audio Quality, DVD Audio Quality, Cassette Video Quality, CD Video Quality, DVD Video Quality

RealTime Grid View, RealTime Chart View,RealTime CSV only View, ReplayView Grid View,ReplayView Chart View, ReplayView CSV only View


Discovery Animal





Consider an application that has to present some data to a user. The source of data could be a device that gives data in realtime mode or a data store. These data could be presented even in a Chart view or in a Grid view or written to a CSV file.

This is the class diagram

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

namespace Statistics
/// <summary>
/// Factory of a family of views that has the same type of provider
/// </summary>
/// <typeparam name="T"></typeparam>
interface IViewFactory<T> where T : IProvider
IChartView GetChartView(string i_name, eChartType i_chartType, T i_provider);
IGridView GetGridView(string i_name, T i_provider);
ICSVTextView GetCSVTextView(string i_name, char i_delimiter, T i_provider);

/// <summary>
/// Provides value for stats from a specific data source
/// </summary>
public interface IProvider
T GetStatValue<T>(int i_index, string i_statName);

/// <summary>
/// Common interface for all views
/// </summary>
public interface IView
String Name { get; }
void RegisterStats(IEnumerable<String> _statNames);
void DeregisterStats();
void OpenView();
void CloseView();
IList<String> Stats { get; }
IProvider ViewProvider { get; set; }

/// <summary>
/// Interface for Chart views
/// </summary>
public interface IChartView : IView
eChartType ChartType { get; set; }

/// <summary>
/// Interface for Grid views
/// </summary>
public interface IGridView : IView

/// <summary>
/// Interface for CSV Text view
/// </summary>
public interface ICSVTextView : IView
char Delimiter { get; }

public enum eChartType

/// <summary>
/// Base implementation common to all providers
/// </summary>
public class BaseProvider : IProvider
public virtual T GetStatValue<T>(int i_index, string i_statName)
if (typeof(T) == typeof(int))
return (T)(object)i_index;
if (typeof(T) == typeof(string))
return (T)(object)string.Format("{0} at position {1}.", i_statName, i_index);
return default(T);

public abstract class BaseView : IView
protected String _name;
protected List<String> _stats;
protected IProvider _provider;
public BaseView(string i_name, IProvider i_provider)
_name = i_name;
_provider = i_provider;
Console.WriteLine(GetType() + " view created!");

public String Name
get { return _name; }

public IProvider ViewProvider
get { return _provider; }
set { _provider = value; }

public virtual void RegisterStats(IEnumerable<String> _statNames) { _stats = new List<String>(_statNames); }
public virtual void DeregisterStats() { if (_stats != null) _stats.Clear(); }
public virtual void OpenView()
StringBuilder _sb = new StringBuilder();
_sb.AppendLine("Statistics in view: " + _name);
foreach (string _stat in _stats)
_sb.AppendLine("\t" + _stat);

public abstract void CloseView();

public IList<string> Stats
get { return _stats; }

public class RealTimeProvider : BaseProvider
public override T GetStatValue<T>(int i_index, string i_statName)
Console.WriteLine(string.Format("GetRealTimeStat {1} at index {0}.", i_statName, i_index));
return base.GetStatValue<T>(i_index, i_statName);

class DataStoreProvider : BaseProvider
public override T GetStatValue<T>(int i_index, string i_statName)
Console.WriteLine(string.Format("Get Stat {1} at index {0} from Datastore.", i_statName, i_index));
return base.GetStatValue<T>(i_index, i_statName);

public class ViewFactory<T> : IViewFactory<T> where T : BaseProvider, new()
protected T m_viewProvider;

public IChartView GetChartView(string i_name, eChartType i_chartType, T i_provider)
return new ChartView<T>(i_name, i_chartType, i_provider);
public IGridView GetGridView(string i_name, T i_provider)
return new GridView<T>(i_name, i_provider);
public ICSVTextView GetCSVTextView(string i_name, char i_delimiter, T i_provider)
return new CSVTextView<T>(i_name, i_delimiter, i_provider);

public T ViewProvider
get { return m_viewProvider; }
set { m_viewProvider = value; }

public class ChartView<T> : BaseView, IChartView where T : BaseProvider
private eChartType m_type;

public ChartView(String _name, eChartType i_type, T i_provider)
: base(_name, i_provider)
m_type = i_type;

#region IChartView Members
public eChartType ChartType
get { return m_type; }
set { m_type = value; }


public override void OpenView()
Console.WriteLine("Open ChartView: " + _name);

public override void CloseView()
Console.WriteLine("Close ChartView: " + _name);

public class GridView<T> : BaseView, IGridView where T : BaseProvider
public GridView(String _name, T i_provider) : base(_name, i_provider) { }
public override void OpenView()
Console.WriteLine("Open GridView: " + _name);

public override void CloseView()
Console.WriteLine("Close GridView: " + _name);

public class CSVTextView<T> : BaseView, ICSVTextView where T : BaseProvider
private readonly char m_delimiter;
public CSVTextView(String _name, char i_delimiter, T i_provider)
: base(_name, i_provider) {
m_delimiter = i_delimiter; }

#region ICSVTextView Members
public char Delimiter
get { return m_delimiter; }

public override void OpenView()
Console.WriteLine("Open CSVTextView: " + _name);

public override void CloseView()
Console.WriteLine("Close CSVTextView: " + _name);

class Client<T> where T : BaseProvider, new()
readonly Queue<IView> _views = new Queue<IView>(4);
public void ClientMain()
IViewFactory<T> _factory = new ViewFactory<T>();
for (int i = 0; i < 12; i++)
IView _newView;
if (i % 3 == 0)
_newView = _factory.GetChartView("ChartView " + i, i % 2 == 0 ? eChartType.kLine : eChartType.kPie, new T());
if (i % 3 == 1)
_newView = _factory.GetGridView("GridView " + i, new T());
_newView = _factory.GetCSVTextView("CSV " + i, '|', new T());

_newView.RegisterStats(new List<String>(new String[] { "Stat 1", "Stat 2" }));

if (_views.Count == 4)
IView _view = _views.Dequeue();

Console.WriteLine("Opened View are: ");
foreach (IView view in _views)
Console.WriteLine(view.Name + view.GetType());
Console.WriteLine("\t Get value for each stats");
for (int i = 0; i < 5; i++)
Console.WriteLine("\t\t At index" + i);
foreach (String stat in view.Stats)
if (i%3 == 0)
Console.Write(view.ViewProvider.GetStatValue<int>(i, stat));
if (i%3 == 1)
Console.Write(view.ViewProvider.GetStatValue<string>(i, stat));
Console.Write(view.ViewProvider.GetStatValue<DateTime>(i, stat));

class StatisticsApp
static void Main()
new Client<RealTimeProvider>().ClientMain();
new Client<DataStoreProvider>().ClientMain();

Abstract Factory pattern is recommended when

• An application should be independent of how its products are created, composed, and represented.
• An application can be configured with one of multiple families of products.
• The constraint requiring products from the same factory to be used together must be enforced.
• The emphasis is on revealing interfaces, not implementations.

luni, 25 ianuarie 2010

Factory Method Pattern

Factory Method Pattern

  • is a way of creating objects, but letting subclasses decide exactly which class to instantiate.
  • instantiates the proper class/es based on current state/info provided by client
  • hide the class name from the place where an object is instantiated

  • CreateInstance()  - factory method which decides which class to be instantiated
  • IResult - defines the interface for the object that factory method creates
  • Result - concreate implementation of IResult
  • Creator - declares the factory method, which returns an object of type IResult
  • Client - class that use Creator to instantiate classes that implement IResult


Client       StatisticsApp
Creator    StatisticsModule
IResult     IView
Result_1   ChartView
Result_2   GridView

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

namespace Statistics
    //Type of IView to be created
    public enum ViewType

    interface IView
        String Name { get; }
        void RegisterStats(IEnumerable<String> _statNames);
        void DeregisterStats();
        void OpenView();
        void CloseView();

    //base implementation for for all View classes
    public abstract class BaseView : IView
        protected String _name;
        protected List<String> _stats;
        public BaseView(string i_name)
            _name = i_name;
            Console.WriteLine(GetType() + " view created!");

        public String Name
            get { return _name; }

        public virtual void RegisterStats(IEnumerable<String> _statNames) { _stats = new List<String>(_statNames); }
        public virtual void DeregisterStats() { if (_stats != null) _stats.Clear(); }
        public virtual void OpenView()
            StringBuilder _sb = new StringBuilder();
            _sb.AppendLine("Statistics in view: " + _name);
            foreach (string _stat in _stats)
                _sb.AppendLine("\t" + _stat);

        public abstract void CloseView();

    public class ChartView : BaseView
        public ChartView(String _name) : base(_name) { }
        public override void OpenView()
            Console.WriteLine("Open ChartView: " + _name);

        public override void CloseView() {
            Console.WriteLine("Close ChartView: " + _name); }

    public class GridView : BaseView
        public GridView(String _name) : base(_name) { }
        public override void OpenView()
            Console.WriteLine("Open GridView: " + _name);

        public override void CloseView()
            Console.WriteLine("Close GridView: " + _name);

    class StatisticsModule
        public static IView CreateInstance(String i_name, ViewType i_viewType)
            switch (i_viewType)
                case ViewType.kChart:
                    return new ChartView(i_name);
                case ViewType.kGrid:
                    return new GridView(i_name);
                    throw new NotSupportedException("Not supported view type");

    class StatisticsApp
        readonly Queue<IView> _views = new Queue<IView>(4);
        internal void Run()
            for (int i = 0; i < 12; i++)
                IView _newView = StatisticsModule.CreateInstance("View " + i, i % 2 == 0 ? ViewType.kGrid : ViewType.kChart);
                _newView.RegisterStats(new List<String>(new String[] { "Stat 1", "Stat 2" }));
                if (_views.Count == 4)
                    IView _view = _views.Dequeue();
            Console.WriteLine("Opened View are: ");
                foreach (IView view in _views)
                    Console.WriteLine(view.Name + view.GetType());
        static void Main()
            StatisticsApp _statsApp = new StatisticsApp();

miercuri, 20 ianuarie 2010

Linq to XML

Linq to XML

  • Functional construction: term used to describe the ability to construct an entire XML hierarchy in a single statement
  • namespace System.Xml.Linq.
  • Linq to XML API is very element centric (dif. from document centric)
  • document centricity eliminated in favor of element centricity
    • in W3C DOM: attributes, comments, CData, section, processing instruction, elements must be created from XmlDocument
  • System.Xml.XmlConvert
    • .ToBoolean()

  • The only classes that could have nodes derived from XNode are XDocument and XElement
  • Halloween problem:
    • there is any problem that occurs by changing data that is being iterated over affect the iteration
    • it can occur, for example, when removing elements from an XML tree
      • solution: move elements that are removed in a cache list
  • XDocument _doc = new XDocument();
    XmlWriter _writer = _doc.CreateWriter();
    XslCompiledTransform _transform = new XslCompiledTransfor();
  • IEnumerable<XElement> _elements = new Element[]
    { new XElement("Element" , "Element A")
    , new XElement("Element" , "Element B") };
    XElement _root = new XElement("Root" ,
    _elements.Select(e => string(e) != "Element A" ? new Element(e.Name, (string)e) : null));
    • null - it is used to do not create an XElement - ignore the iteration



  • XML Documents are not a must anymore (to create attributes, comments, ... )
  • You can read, save a doc without needing a Document object
  • Namespaces are out
    • inside, no longer exists
  • IEnumerable<XElements> _members = xDocument.Element("Team StatViewer").Elements("Member");
  • XDocument _doc = new XDocument(
    new XDeclaration("1.0", "UTF-8", "yes")
    , new XDocumentType("StatViewer", null, "StatViewer.dtd", null)
    , new XProcessingInstruction("Team StatViewer", "to be printed")
    , new XElement ( "Team StatViewer"));
  • .Save()
  • .SaveOptions.DisableFormatting
  • .Load()


  • consist of
    • namespace (XNamespace)
    • local name (LocalName)
  • there is no need to directly create a name
    • has no public ctor
  • XNamespace _namespace = "";
  • XElement _member = new XElement(_namespace + "Member");


  • XElement _team = new XElement ( "Team StatViewer" 
                                 , new XElement ("Name" , "George Lache")
                                 , new XElement ("Position" , "Senior Dev"));
  • _team.ToString();
  • calling .ToString() method of an element outputs the XML string itself and not object type
    • XElement _george = new XElement ("Name" , "George Lache");
      //"Name" is a XName
      //"George Lache is a XText
      Console.WriteLine(_george); // <Name>George Lache</Name>
      Console.WriteLine((string)_george); // George Lache
      - return a XText
  • XElement _team = new XElement ( "Team StatViewer"
    ,  members.Select ( m =>
    new XElement("Member",
    new XAttribute("Position" , m.Position),
    new XElement("Name", m.Name)));
  • .Add(XAttribute), .Add(XComment)
  • .Save()
  • .Load()
  • .LoadOptions
    • .Name
    • .PreserveWhitespace
    • .SetLineInfo //set line & position
      • IXmlLineInfo
      • ((IXmlLineInfo)name)
        • .LineNumber
        • .LinePosition
    • SetBaseUri()
  • .Parse()
    • used for parsing XML string
    • XElement.Parse(_xmlText);
  • .AncestorsAndSelf();
  • DescendantsAndSelf();


  • creates comments
  • XElement _member = ...;
    XComment _comm = new XComment("This is StatViewer team presentation");


  • CData content
  • XCData _cData = new XCData("<h1>Invalidate member</h1>"
    , "<elem>!CData[<h1> .... </h1>] </elem>")


  • it is an abstract class - cannot be instantiated
  • subclasses: XComment, XContainer, XDocumentType, XProcessingInstruction, XText
  • .NextNode()
    • traverse forward
  • .PreviousNode()
    • traverse barward
  • .Ancestors()
    • recursively traverses up the XML tree
  • .NodesAfterSelf()
    • traversing forward the current node
  • .ElementsAfterSelf()
  • .NodesBeforeSelf()
  • .ElementsBeforeSelf()


  • defers elecution of the XML tree construction
  • when you create an XML tree using XStreamingElement, a reference to the query variable is stored in the XML tree without being iterated.
  • string _names = {"George Lache", "Anca Suciu", "Marian Gheorghe"};
    XStreamingElement members = new XStreamingElement("Members",
    from n in _names
    select new XStreamingElement("Name", n));


  • XText _text = new XText("George Lache");


  • .Document
    • obtains the XML Document
  • .Parent
  • .AddAnnotation()
  • .Annotation()
  • .Annotations()
  • .RemoveAnnotations()


  • Represents a node that can contain other nodes.
  • This class provides functionality such as finding the next or previous sibling node, or enumerating the direct children of a node.
  • The two classes that derive from XContainer are XDocument and XElement
  • .Nodes()
    • _doc.Nodes().OfType<XElement>
  • .Attributes()
  • .Elements()
    • accessing an element's child elements
  • Element()
    • _member.Element("Name");
  • .Elements()
  • .Descendants();
  • .Add()
  • .AddLast()
  • .AddFirst()

How to change an XML?

  • XElement
    • .SetElementValue()
    • .RemoveAll()
      • deletes the content of an element, but not he element itself
    • .Value
      • also, for XText, XComment
      • _member.Element("Name").Single().Name = "George";
    • .ReplaceAll()
      • replaces an element's entire subtree of XML
    • SetElementValue()
      • it is a method on a parent element to affect its content (child elements)
      • if you pass null the child elements will be removed
      • it will affect only the first child element that matches the specified name
      • Sample:
        _member.SetElementValue("Name", "George V. Lache");
      • it can be used for adding/updating/removing an element
    • .Attribute()
    • .Attributes()
    • .Add()
    • .AddFirst()
    • .AddBeforeThis()
    • .AddAfterThis()
    • .AddAttributeValue()
  • XContainer: .Add(), .AddLast(), .AddFirst()
  • XNode:
    • .AddBeforeSelf()
      • inserts a node into a node's list of child nodes in a specific location
    • .AddAfterSelf(),
    • .Remove()
      • Remove any node as well as its child nodes and its attributes from an XML tree
      • _members.Descendants().Where(m => m.Name.Contains("George")).Remove();
  • XDocumentType
    • .Name
      • update document type
    • .PublicId // "http:// ... .DTD"
    • .SystemId
  • XProcessingInstruction
    • Sample: new XProcessingInstruction("Team StatViewer", "to be printed")
    • .Target //"Team StatViewer"
    • .Data //"to be printed"
  • XAttribude
    • does not inherit from XNode
    • .FirstAttribute()
    • .LastAttribute()
    • .NextAttribute()
    • .PreviousAttibute()
    • .Remove()
      • IEnumerable<T>.Remove()
      • _member.Attributes().Remove()
    • to update:
      • .Value
      • .SetAttributeValue()
        • also, used for updating and deleting

XML Annotation

  • provides the ability to associate a user data object with any class inheriting from XObject class via annotations
    • assigns whatever data type to an element, document, ...
  • XObject
    • .AddAnnotation()
    • .Annotation()
    • .Annotations()
    • .RemoveAnnotations()
  • Sample:
    MemberClass _memberClass = new MemberClass();

XML Events

  • the events will be raised on the object if that object or any descendant object is changing
  • XObject
    • .Changing
      • myXObj.Changing = new EventHandler<XObjectChangeEventArgs>(MyHandlingMethod);
    • Changed
  • XObjectChangeEventArgs
    • .ObjectChange
      • of type XObjectChange
        • .Add
        • .Name
        • .Remove
        • .Value
  • !!! when you change the string value of an element, an XText object is removed and then added back

Linq to XML Operators

  • Xml Operators
    • are extension methods
    • are defined in System.Xml.Linq.Extension class
  • extension methods are somehow equivalent to operators
  • Element
    • IEnumerable<XElement> Element<T>
                (this IEnumerable<T> source)
      where T : XElement
  • Ancestors
    • IEnumerable<XElement> Ancestors<T>
                 (this IEnumerable<T> source)
      [,Xname name)]
                 where T : XNode
    • _xDoc.Element("Members").Descendand("Name").Ancestors()
  • AncestorsAndSelf
    • it can be called on XElement
      • as opposed to Ancestor which is called on Node
  • Attributes
    • retrives a sequence containint the attributes of each source element
  • DescendantNodes
    • return a sequence containing the descendant nodes if each element or document
    • public static IEnumerable<Xnode> DescendingNodes<T>
                                   (this IEnumerable<T> source)
                         where T : XContainer
  • DescendantNodesAndSelf
  • Descendants
    • can be called on a sequence of elements or documents and return a sequence of elements
  • DescendantsAndSelf
  • Elements
    • returns a sequence of elements containing each source element's or document's child element
    • returns only the immediate child elements of each element in the source sequence
  • InDocumentOrder
    • returns a sequence containing each source node's child nodes in document order
  • Nodes
    • returns only the immediate child elements
    • public static IEnumerable<Xnode> Nodes<T>
                                   (this IEnumerable<T> source)
                         where T : XContainer
  • Remove


  • in system.Xml.Schema.Extension
  • .Validate
    • (this XDocument [or XElement or XAttribure] source,
      XmlSchemeSet schemas,
      ValidationEventHandler validationEH)
      [,bool addShemaInfo)]
  • .GetSchemaInfo
  • XmlSchemaValidationException

How to obtain an XML Schema (XSD schema file (.xsd))?

XmlSchemaInference inference = new XmlSchemaInference();
XmlSchemaSet schemaSet = inference.InferSchema ( new XmlTextReader ("StatViewer.xml") );
XmlWriter writer = XmlWriter.Create("StatViewer.xsd");
foreach(XmlSchema schema in schemaSet.Schemas)

    (o , validExceptArgs ) =>
            Console.WriteLine(o.GetType().Name +validExceptArgs.Message);


  • XPath allows you to create a query by assembling a number of expressions and predicates, each one acting on a node-set 
  • XPathNavigator
  • System.Xml.XPath.Extension class
  • .CreateNavigator
    (this XNode node
    [, XmlNameTable nameTable])
  • XPathEvaluate()
  • XPathSelectElement()
  • XPathSelectElements()
  • Sample:
    • xDocument.XPathSelectElement("//StatViewer/Members/Member[Name = 'George Lache']")

marți, 19 ianuarie 2010

Linq: Operators

Linq: Operators


  • query expression syntax
  • Components
    • Linq to Objects
    • Linq to XML
    • Linq to DataSet
    • Linq to SQL
    • Linq to Entities
  • Sample:
    • .Cast<T>
    • .OfType<T> - returns only the elements that can be cast.
  • "deferred queries"
  • DataContext log: Northwind _db = ... ; _db.Log = Console.Out;
  • Lambda Expression
    (param1, param2, ....) => expr
    { ...;
    ...} return (lambda_expression_type);
  • Expression Tree
    numbers.Where(i => 1>4)
    .OrderBy(i => i)
    • There are expression
      • of a method delegate: returns IEnumerable<T>
      • expression of a tree: returns IQueryable<T>
  • var
    • var person = new { FirstName = "George", LastName ="Lache" } -> person is an anonymous type
  • Object Initialization:
    • Address _address = new Address
      { address = "Anton Bacalbasa, no. 20",
      city ="Bucharest" };
  • Collection initialization: List<string> _myFam = new List<string> { "Bianca", "George", "Alina" };
  • Extension Methods
    • .Where; .GroupBy
    • static methods of a static class
    • call as an instance method of a different class
      public static class Utils
      public static double ToDouble(this string s)
      return Double.Parse(s);
  • Partial Methods
    • are in partial classes
    • have "partial" modifier
    • are private/ but do not specify private modifier
    • return void
    • may be unimplemented
    • may be static
    • may have arguments
  • Query Expression
    • SQL-like syntax
    • Sample:
      from s in students
      where s.Name.Length < 6 or
      select s
      students.Where (s => s.Name.Length < 6)
      .Select(s => s);
    • Order of statements:
      • must begin with "from" clause
      • contains 0 or more from/let/where ....
        into clauses.
      • followed by "Order by" (asc, desc)
      • select/group
      • 0 or more join
    • Sample:
      from c in customer
      let FullName = c.FirstName + " " + c.LastName
      select new { c.FullName, c.City }

      .OrderByDescending( c => c.FullName )
      .OrderBy ( c = > c.State ). ThebBy(c => c.City)
      .GroupBy (c => c.Country)
    • a collection must implement IEnumerable<T> or IEnumerable in order to be quaryable with Linq
    • Sequence - logical term for a collection implementing IEnumerable<T>
      • System.Linq.Enumerable
        • static class
        • contains extension methods
      • use .Cast() or .OfType() end with non-generics C# collections
  • yield
    • the way the queries are deferred
  • Don't assume that queries are bug free
  • Different data types which cache the results:
    • .ToList()
    • .ToArray()
    • .ToDictionary()
    • .ToLoopup()
  • Func delegate
    • always, the last parameter is the returned parameter type
    • public delegate TR Func<TR>()
    • public delegate TR Func<T0, TR>(T0 _t0)
    • public delegate TR Func<T0, T1 TR>(T0 _t0, T1 _t1)
    • Sample: Func<int, bool> GreaterThen2 = i => i>2

Deferred Operators

  • return a type of:
    • IEnumerable<T>
    • IOrderedEnumerable<T>


  • Where
    • has 2 prototypes
    • second one:
      • public static IEnumerable<T> Where<T> (
        this IEnumerable<T> source,
        Func<T, int, bool> predicate);
      • int type stands for the index number for the elements from the input sequence
      • var boyNames = names.Where((n) => n.Gender == Gender.Boy).Select((n) => new { n.Name });


  • returns an output sequence of elements that are generated by selecting elements
  • Select
    • public static IEnumerable<T> Select<T,S> (
      this IEnumerable<T> source,
      Func<T, S> selector);
  • SelectMany
    • public static IEnumerable<T> SelectMany<T,S> (
      this IEnumerable<T> source,
      Func<T, IEnumerable<S>> selector);
    • input: a sequence of elements of type T
    • returns:: when enumerated, enumerated the input source sequence
    • IEnumerable<char> chars = "George Lache".SelectMany(n => n.ToArray());
    • it is useful to concatenate multiple sequence together


- subset of a input sequence
  • Take
    • students.Take(3);
    • returns a specific no. of elements from the input sequence, starting from beginning of the sequence
    • public static IEnumerable<T> Take<T> (

      this IEnumerable<T> source,
      int count);
  • TakeWhile
    • yields elements from an input sequence while some condition is true
    • public static IEnumerable<T> TakeWhile<T> (

      this IEnumerable<T> source,
      Func<T, int, bool> predicate);
  • Skip
    • skips a specific no. of elements from the input sequence starting from beginning of the sequence and yield the rest
    • studends.Skip(3);
  • SkipWhile


  • Concat
  • public static IEnumerable<T> TakeWhile<T> (

    this IEnumerable<T> first,
    IEnumerable<T> second);
  • alternative:
    { students.Take(3),
    .Skip(3) }


  • OrderBy
  • OrderByDescending
  • ThenBy
  • ThenByDescending
  • Result of OrderBy and OrderByDescending cannot be passed to another call of OrderBy or OrderByDescending
  • the sorting performed by OrderBy and OrderByDescending is unstable
  • public static IOrderedEnumerable<T> OrderBy<T,K> (

    this IEnumerable<T> source,
    Func<T, K> keySelector)
    where K : IComparable<K>;
  • students.OrderBy(s => s.Name.Length).ThenBy(s => s.City);
  • ThenBy and ThenByDescending are stable sort
  • public static IOrderedEnumerable<T> ThenBy<T,K> (

    this IEnumerable<T> source,
    Func<T, K> keySelector,
    IComparer<K> comparer);
  • Reverse
    • public static IOrderedEnumerable<T> Reverse<T> (

      this IEnumerable<T> source);


  • Join
    • performs an inner equijoin in two sequences based on keys extracted from each element in the sequences.
    • public static IEnumerable<V> Join<T,U,K,V> (
      this IEnumerable<T> outer,
      IEnumerable<U> inner,
      Func<T,K> outerKeySelector,
      Func<U,K> innerKeySelector,
      Func<T,U,V> resultSelector);
  • GroupJoin
    • performs a grouped join on two sequences based on key matching multiple inner sequence elements for a single sequence element result
    • public static IEnumerable<V> GoupJoin<T,U,K,V> (

      this IEnumerable<T> outer,

      IEnumerable<U> inner,

      Func<T,K> outerKeySelector,

      Func<U,K> innerKeySelector,

      IEnumerable<U>,V> resultSelector);
    • "one record from each employee contains the sum of all of that employee 's options records"


  • groups elements of a sequence together by a common key
  • IGrouping<K,T> : IEnumerable<T>
    • K Key { get; }
  • EqualityComparerDefault
  • GroupBy
    • public static IEnumerable<IGrouping<K,T>> GroupBy<T,K> (

      this IEnumerable<T> source,
      Func<T, K> keySelector)
      [IEqualityComparer<K> comparer]
  • interface IEqualityComparer<T> {
    bool Equals(T x, T y);

    int GetHashCode(T x); }


  • performs mathematical set-type operations on sequence
  • !!! Do not work properly for DataSets
  • Distinct
    • removes duplicate elements from input sequence
  • Union
    • returns a sequence of set union of two sources sequences
    • from second sequence are taken only the elements that are not found in the first sequence (!= from Concat)
  • Intersect
  • Except


  • Cast
    • it is used to cast every element of an input string sequence to an output sequence of the specified type
    • public static IEnumerable<T> Cast<T> (

      this IEnumerable source);
    • if an element can not be cast to type T then an exception will be thrown
    • Sample:
      ArrayList employees = new ...;
  • OfType
    • is used to build an output sequence containing only the elements that can be successfully cast to a specific type
  • AsEnumerable
    • simply cause its input sequence of type IEnumerable<T> to be returned as type IEnumerable<T>
    • public static IEnumerable<T> AsEnumerable<T> (

      this IEnumerable source);
    • it is changing the output sequence type at compile time
    • var _customers =
      (from c in db.Customers
      where c.City = "Bucharest"
      select c)


  • allows you to retrieve single element from an input collection
  • DefaultIfEmpty
    • returns a sequence containing a default element if the input source sequence is empty
    • <=> default<T>
      • var eo = employees
        e => e.Id,
        o => o.Id,
        (e,o) => os
        .Select (o => new { id =,
        name = ...
        option = o!= null > o.Count :0 }))
        .SelectMany(r => r);


  • Range
    • generates a sequence of integers
    • public static IEnumerable<int> Range (int start, int end);
    • !!! It is not an extension method. It is a static method called on System.Linq.Enumerable
      • IEnumerable<int> _ints = Enumerable.Range(1, 10);
  • Repeat
    • generates a sequence by repeating a specific element for a specified no. of times
    • public static IEnumerable<T> Repeat<T>(T element, int count);
  • Empty
    • returns an empty sequence of specific type (0 elements of type T)
    • IEnumerable<string> tempStrings = Enumerable.Empty<string>();

Non Deferred Operators

Standard query operators

  • have a return data type other then IEnumerable<T> or IOrderedSequence<T>
  • ToArray
    • in C# 3.0 arrays implement IEnumerable<T> interface
  • ToList
    • returns a list of T
  • ToDictionary
    • creates a dictionary of <K,T>
    • public dictionary <K, T> ToDictionary<T,K> (
      this IEnumerable<T> source,
      Func<T,K> keySelector
      [IEqualityComparer<K> comparer)]
  • ToLookup
    • Lookup collection: allows multiple elements to be stored/retrieved with a key


  • SequenceEqual
    • determines if two input sequence are equal


  • First
    • first element of a sequence [that matches a predicate]
  • FirstOrDefault
  • Last
  • LastOrDefault
  • Single
    • returns only one element of a sequence [matching a predicate]
    • throws InvalidOperationException
      • if source sequence is empty
      • predicate never returns true
    • !!! does not produce a sequence
    • public static T Single<T> (
      this IEnumerable<T> source
      [Func<T,bool> predicate])
  • ElementAt
    • returns element from source sequence at the specific index
  • ElementAtOrDefaut
    • if source sequence implement IList<T> then IList<T> is used to retrieve the indexed element, else the sequence is enumerated


  • allows you to perform qualification type operation on input sequence
  • Any
    • returns true if any element of an input sequence matches a condition
    • public static T Any<T> (

      this IEnumerable<T> source

      [Func<T,bool> predicate])
  • All
    • returns true if every element of an input sequence matches a condition
  • Contains
    • returns true if any element of an input sequence matches a specific value
    • first checks if the sequence implement ICollection<T>, else enumerates the collection
    • EqualityComparer<K>.Default


  • Count
    • returns int
    • no. of elements in the input sequence
  • LongCount
    • returns long
    • public static T LongCount<T> (

      this IEnumerable<T> source

      [Func<T,bool> predicate])
  • Sum
    • returns the sum of numeric values
    • public static Numeric Sum[<T>] (

      this IEnumerable<Numeric > source

      T, Numeric> selector]);
      • where Numeric could be int, long, double, decimal, int?, long?, ...
    • colors.Sum(c = > c.Green)
  • Min
  • Max
  • Average
    • result will be double or double?
  • Aggregate
    • performs user - specified function on each element of an input sequence
    • public static T Aggregate<T> (

      this IEnumerable<T> source

      [Func<T,T,T> funct])
    • Factorial: listOfInt.Aggregate(av, e => av*e)
    • Sum: listOfInt.Aggregate(av, e => av + e)

vineri, 15 ianuarie 2010

C# Programming Interview Questions

General Questions

  1. Does C# support multiple-inheritance? No.
  2. Who is a protected class-level variable available to? It is available to any derived class.
  3. Are private class-level variables inherited? Yes, but they are not accessible.  Although they are not visible or accessible via the class interface, they are inherited.
  4. Describe the accessibility modifier “protected internal”. It is available to classes that are within the same assembly or derived from the specified base class.
  5. What’s the top .NET class that everything is derived from? System.Object.
  6. What does the term immutable mean? The data value may not be changed.  Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.
  7. What’s the difference between System.String and System.Text.StringBuilder classes? System.String is immutable.  System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
  8. What’s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in cases where there is a large amount of string manipulation.  Strings are immutable, so each time a string is changed, a new instance in memory is created.
  9. Can you store multiple data types in System.Array? No.
  10. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
    Clone() method returns a new array (a shallow copy) object containing
    all the elements in the original array.  The CopyTo() method copies the
    elements into another existing array.  Both perform a shallow copy.  A
    shallow copy means the contents (each array element) contains
    references to the same object as the elements in the original array.  A
    deep copy (which neither of these methods performs) would create a new
    instance of each element's object, resulting in a different, yet
    identacle object.
  11. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods.
  12. What’s the .NET collection class that allows an element to be accessed using a unique key? HashTable, Dictionary<,>.
  13. What class is underneath the SortedList class? A sorted HashTable. 
  14. Will the finally block get executed if an exception has not occurred? Yes.
  15. What’s the C# syntax to catch any possible exception? A
    catch block that catches the exception of type System.Exception.  You
    can also omit the parameter data type in this case and just write catch
  16. Can multiple catch blocks be executed for a single try statement? No.  Once the proper catch block processed, control is transferred to the finally block (if there are any).
  17. Explain the three services model commonly know as a three-tier application. Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).
  18. Why do I get a syntax error when trying to declare a variable called checked? - The word checked is a keyword in C#.
  19. Is there a way to force garbage collection? - Yes. Set all
    references to null and then call System.GC.Collect(). If you need to
    have some objects destructed, and System.GC.Collect() doesn’t seem to
    be doing it for you, you can force finalizers to be run by setting all
    the references to the object to null and then calling
  20. Explain the "yield" keyword. What is the compiler doing internally?
  21. What is an intern pool ?

    Defination: A performance optimization based on using collections of pre-allocated resources such as objects or database connections
    the advent of the .NET platform writing code that pools objects and
    threads has become a simple task. By using the Threading and Collections namespaces you can create robust object pooling applications. This could also be done by implementing COM+ interop interfaces into your code
  22. How many generations of garbage collection are there? 3
  23. Why are catch all exception handlers bad? When/Why might you use them?
  24. How do you choose 1 entry point when C# project has more Main( ) method? CSC /main:classname filename.cs
  25. How do you refer parent classes in C#? Base
  26. What is difference between typeof() and .GetType()?
  27. What is an indexer in C#? 

Class Questions

  1. What is the syntax to inherit from a class in C#?  Place a colon and then the name of the base class. Example: class MyNewClass : MyBaseClass
  2. Can you prevent your class from being inherited by another class? Yes.  The keyword “sealed” will prevent the class from being inherited.
  3. Can you allow a class to be inherited, but prevent the method from being over-ridden? Yes.  Just leave the class public and make the method sealed.
  4. What’s an abstract class? A class that cannot be instantiated.  An abstract class is a class that must be inherited and have the methods overridden.  An abstract class is essentially a blueprint for a class without any implementation.
  5. When do you absolutely have to declare a class as abstract?
    1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
    2.  When at least one of the methods in the class is abstract.
  6. What is an interface class? Interfaces,
    like classes, define a set of properties, methods, and events. But
    unlike classes, interfaces do not provide implementation. They are
    implemented by classes, and defined as separate entities from classes.
  7. Why can’t you specify the accessibility modifier for methods inside the interface? They all must be public, and are therefore public by default.
  8. Can you inherit multiple interfaces? Yes.  .NET does support multiple interfaces.
  9. What happens if you inherit multiple interfaces and they have conflicting method names?
  10. What’s the difference between an interface and abstract class?  In an interface class, all methods are abstract - there is no implementation.  In an abstract class some methods can be concrete.  In an interface class, no accessibility modifiers are allowed.  An abstract class may have accessibility modifiers.
  11. What is the difference between a Struct and a Class? Structs
    are value-type variables and are thus saved on the stack, additional
    overhead but faster retrieval.  Another difference is that structs cannot inherit.

Method and Property Questions

  1. What’s the implicit name of the parameter that gets passed into the set method/property of a class? Value. The data type of the value parameter is defined by whatever data type the property is declared as.
  2. What does the keyword “virtual” declare for a method or property?  The method or property can be overridden.
  3. How is method overriding different from method overloading?  When overriding a method, you change the behavior of the method for the derived class.  Overloading a method simply involves having another method with the same name within the class.
  4. Can you declare an override method to be static if the original method is not static?  No.  The signature of the virtual method must remain the same.  (Note: Only the keyword virtual is changed to keyword override)
  5. What are the different ways a method can be overloaded? Different parameter data types, different number of parameters, different order of parameters.
  6. If a base class has a number of overloaded
    constructors, and an inheriting class has a number of overloaded
    constructors; can you enforce a call from an inherited constructor to a
    specific base constructor?
    Yes, just place a colon, and
    then keyword base (parameter list to invoke the appropriate
    constructor) in the overloaded constructor definition inside the
    inherited class.

Events and Delegates

  1. What’s a delegate?  A delegate object encapsulates a reference to a method. A strongly typed function pointer.
  2. What’s a multicast delegate? A delegate that has multiple handlers assigned to it.  Each assigned handler (method) is called.

XML Documentation Questions

  1. Is XML case-sensitive? Yes.
  2. What’s the difference between // comments, /* */ comments and /// comments? Single-line comments, multi-line comments, and XML documentation comments.
  3. How do you generate documentation from the C# file commented properly with a command-line compiler?  Compile it with the /doc switch.

Debugging and Testing Questions

  1. What debugging tools come with the .NET SDK?
    1.   CorDBG – command-line debugger.  To use CorDbg, you must compile the original C# file using the /debug switch.
    2.   DbgCLR – graphic debugger.  Visual Studio .NET uses the DbgCLR.
  2. What does assert() method do? In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false.  The program proceeds without any interruption if the condition is true.
  3. What’s the difference between the Debug class and Trace class? Documentation looks the same.  Use Debug class for debug builds, use Trace class for both debug and release builds.
  4. Why are there five tracing levels in System.Diagnostics.TraceSwitcher?  The tracing dumps can be quite verbose.  For applications that are constantly running you run the risk of overloading the machine and the hard drive.  Five levels range from None to Verbose, allowing you to fine-tune the tracing activities.
  5. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor. 
  6. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger.
  7. What are three test cases you should go through in unit testing?
    1.       Positive test cases (correct data, correct output).
    2.       Negative test cases (broken or missing data, proper handling).
    3.       Exception test cases (exceptions are thrown and caught properly).
  8. Can you change the value of a variable while debugging a C# application?  Yes.  If you are debugging via Visual Studio.NET, just go to Immediate window.

ADO.NET and Database Questions

  1. What is the role of the DataReader class in ADO.NET connections?  It
    returns a read-only, forward-only rowset from the data source.  A
    DataReader provides fast access when a forward-only sequential read is
  2. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
    data provider is high-speed and robust, but requires SQL Server license
    purchased from Microsoft. OLE-DB.NET is universal for accessing other
    sources, like Oracle, DB2, Microsoft Access and Informix.  OLE-DB.NET is a .NET layer on top of the OLE layer, so it’s not as fastest and efficient as SqlServer.NET.
  3. What is the wildcard character in SQL? Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.
  4. Explain ACID rule of thumb for transactions.
    A transaction must be:
    1.       Atomic - it is one unit of work and does not dependent on previous and following transactions.
    2.       Consistent - data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t.
    3.       Isolated - no transaction sees the intermediate results of the current transaction).
    4.       Durable - the values persist if the data had been committed even if the system crashes right after.
  5. What connections does Microsoft SQL Server support?
    Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password).
  6. Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted?
    Authentication is trusted because the username and password are checked
    with the Active Directory, the SQL Server authentication is untrusted,
    since SQL Server is the only verifier participating in the transaction.
  7. What does the Initial Catalog parameter define in the connection string? The database name to connect to.
  8. What does the Dispose method do with the connection object?
  9. What is a pre-requisite for connection pooling? Multiple
    processes must agree that they will share the same connection, where
    every parameter is the same, including the security settings.  The connection string must be identical.

Assembly Questions

  1. How is the DLL Hell problem solved in .NET?  Assembly
    versioning allows the application to specify not only the library it
    needs to run (which was available under Win32), but also the version of
    the assembly.
  2. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.
  3. What is a satellite assembly? When
    you write a multilingual or multi-cultural application in .NET, and
    want to distribute the core application separately from the localized
    modules, the localized assemblies that modify the core application are
    called satellite assemblies.
  4. What namespaces are necessary to create a localized application? System.Globalization and System.Resources.
  5. What is the smallest unit of execution in .NET? an Assembly.
  6. When should you call the garbage collector in .NET? As
    a good rule, you should not call the garbage collector.  However,
    you could call the garbage collector when you are done using a large
    object (or set of objects) to force the garbage collector to dispose of
    those very large objects from memory.  However, this is usually not a
    good practice.
  7. How do you convert a value-type to a reference-type? Use Boxing.
  8. What happens in memory when you Box and Unbox a value-type? Boxing
    converts a value-type to a reference-type, thus storing the object on
    the heap.  Unboxing converts a reference-type to a value-type, thus
    storing the value on the stack.
  9. Why does DllImport not work for me? - All methods marked with the DllImport attribute must be marked as public static extern
  10. What’s a strong name? A strong name includes the name of the assembly, version number, culture identity, and a public key token.


  1. Write a simple Windows Forms MessageBox statement. System.Windows.Forms.MessageBox.Show("Hello, Windows Forms");
  2. How to find out how many calender days are there between two dates in
DateTime t1 = new DateTime(2008, 5, 13);
DateTime t2 = new DateTime(2004, 2, 22);

TimeSpan span = (t1 > t2 ? t1 - t2 : t2 - t1); Console.WriteLine(span.TotalDays);
  1. Which debugging window allows you to see the methods called in the order they were called? The Call Stack
  2. How you hide a form when Close button is pressed? Use in method registered to closing event of the form put the following code: public override void OnClosing(CancelEventArgs e) { e.Cancel = true; Hide(); }
  3. Can you write a class without specifying namespace? Which namespace does it belong to by default? Yes, you can, then the class belongs to global namespace which has no
    name. For commercial products, naturally, you wouldn’t want global
  4. How can you save the desired properties of Windows Forms application? .config files in .NET are supported through the API to allow storing
    and retrieving information. They are nothing more than simple XML
    files, sort of like what .ini files were before for Win32 apps.
  5. So how do you retrieve the customized properties of a .NET application
    from XML .config file?
    Initialize an instance of AppSettingsReader
    class. Call the GetValue method of AppSettingsReader class, passing in
    the name of the property and the type expected. Assign the result to
    the appropriate variable.
  6. My progress bar freezes up and dialog window shows blank, when an
    intensive background process takes over.
    Yes, you should’ve
    multi-threaded your GUI, with taskbar and main form being one thread,
    and the background process being the other.
  7. How can I run an EXE from within my application? 
    Use the Process class found in the System.Diagnostics namespace.


    Process m_process = new Process();
    m_process.StartInfo.FileName = @"Notepad.exe";
    m_process.StartInfo.Arguments = "";
  8. How can I find all programs with a GUI (not just arbitrary windows) that are running on my local machine? 
    You could use EnumWindows with p/Invoke, but using the static
    Process.GetProcesses() found in the System.Diagnostics namespace will
    avoid the interop overhead.
    foreach ( Process p in Process.GetProcesses(System.Environment.MachineNam e) )

       if( p.MainWindowHandle != IntPtr.Zero)
    //this is a GUI app 
      Console.WriteLine( p ); // string s = p.ToString();

  9. How can I make sure there is only one instance of my application running?

    Use Process class in System.Diagnostics to implement this
    functionality using code such as

    public static Process RunningInstance()

      Process current = Process.GetCurrentProcess();
      Process[] processes = Process.GetProcessesByName (current.ProcessName);
      //Loop through the running processes in with the same name

    foreach (Process process in processes)
         //Ignore the current process
         if (process.Id != current.Id)
             //Make sure that the process is running from the exe file.
             if (Assembly.GetExecutingAssembly().Location.Replace( "/", "\\") == current.MainModule.FileName)
                    //Return the other process instance.
                    return process;

    //No other instance was found, return null.

    return null;

  10. How do I get the path to my running EXE? Application.ExecutablePath
  11. How can I trigger a Paint event in System.Drawing? Use Invalidate property.


  1. How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#? lock, Monitor.Enter() .Exit()


  1. What is the Lazy Design Pattern? The approach of the Lazy Design Pattern is not to create objects until
    a specific requirement matches, and when it matches, object
    creation is triggered.