Thursday, December 27, 2012

Explicit Interface Implementation

A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface.

This example declares an interface IDimensions, and a class Box, which explicitly implements the interface members Length and Width. The members are accessed through the interface instance myDimensions.
// explicit1.cs
interface IDimensions 
{
   float Length();
   float Width();
}
 
class Box : IDimensions 
{
   float lengthInches;
   float widthInches;
 
   public Box(float length, float width) 
   {
      lengthInches = length;
      widthInches = width;
   }
   // Explicit interface member implementation: 
   float IDimensions.Length() 
   {
      return lengthInches;
   }
   // Explicit interface member implementation:
   float IDimensions.Width() 
   {
      return widthInches;      
   }
 
   public static void Main() 
   {
      // Declare a class instance "myBox":
      Box myBox = new Box(30.0f, 20.0f);
      // Declare an interface instance "myDimensions":
      IDimensions myDimensions = (IDimensions) myBox;
      // Print out the dimensions of the box:
      /* The following commented lines would produce compilation 
         errors because they try to access an explicitly implemented
         interface member from a class instance:                   */
      //System.Console.WriteLine("Length: {0}", myBox.Length());
      //System.Console.WriteLine("Width: {0}", myBox.Width());
      /* Print out the dimensions of the box by calling the methods 
         from an instance of the interface:                         */
      System.Console.WriteLine("Length: {0}", myDimensions.Length());
      System.Console.WriteLine("Width: {0}", myDimensions.Width());
   }
}
 
OUT PUT  
Length: 30
Width: 20
 
   
Explicit interface implementation also allows the programmer to inherit two interfaces that share the same member names and give each interface member a separate implementation. This example displays the dimensions of a box in both metric and English units. The Box class inherits two interfaces IEnglishDimensions and IMetricDimensions, which represent the different measurement systems. Both interfaces have identical member names, Length and Width.

// explicit2.cs
// Declare the English units interface:
interface IEnglishDimensions 
{
   float Length();
   float Width();
}
// Declare the metric units interface:
interface IMetricDimensions 
{
   float Length();
   float Width();
}
// Declare the "Box" class that implements the two interfaces:
// IEnglishDimensions and IMetricDimensions:
class Box : IEnglishDimensions, IMetricDimensions 
{
   float lengthInches;
   float widthInches;
   public Box(float length, float width) 
   {
      lengthInches = length;
      widthInches = width;
   }
// Explicitly implement the members of IEnglishDimensions:
   float IEnglishDimensions.Length() 
   {
      return lengthInches;
   }
   float IEnglishDimensions.Width() 
   {
      return widthInches;      
   }
// Explicitly implement the members of IMetricDimensions:
   float IMetricDimensions.Length() 
   {
      return lengthInches * 2.54f;
   }
   float IMetricDimensions.Width() 
   {
      return widthInches * 2.54f;
   }
   public static void Main() 
   {
      // Declare a class instance "myBox":
      Box myBox = new Box(30.0f, 20.0f);
      // Declare an instance of the English units interface:
      IEnglishDimensions eDimensions = (IEnglishDimensions) myBox;
      // Declare an instance of the metric units interface:
      IMetricDimensions mDimensions = (IMetricDimensions) myBox;
      // Print dimensions in English units:
      System.Console.WriteLine("Length(in): {0}", eDimensions.Length());
      System.Console.WriteLine("Width (in): {0}", eDimensions.Width());
      // Print dimensions in metric units:
      System.Console.WriteLine("Length(cm): {0}", mDimensions.Length());
      System.Console.WriteLine("Width (cm): {0}", mDimensions.Width());
   }
}
 
OUT PUT   
Length(in): 30
Width (in): 20
Length(cm): 76.2
Width (cm): 50.8


Default implementation of methods
If you want to make the default measurements in English units, implement the methods Length and Width normally, and explicitly implement the Length and Width methods from the IMetricDimensions interface:
// Normal implementation:
public float Length()
{
   return lengthInches;
}
public float Width()
{
   return widthInches;
}
// Explicit implementation:
float IMetricDimensions.Length() 
{
   return lengthInches * 2.54f;
}
float IMetricDimensions.Width() 
{
   return widthInches * 2.54f;
}
 
 
In this case, you can access the English units from the class instance and access the metric units from the interface instance:
System.Console.WriteLine("Length(in): {0}", myBox.Length());
System.Console.WriteLine("Width (in): {0}", myBox.Width());  
System.Console.WriteLine("Length(cm): {0}", mDimensions.Length());
System.Console.WriteLine("Width (cm): {0}", mDimensions.Width());

Tuesday, December 25, 2012

Encalsulation vs Abstraction

  • Encapsulation is a procedure of covering up of the data & functions into a single unit called as class
  • An encapsulated object is often called an abstract data type.
  • Encapsulation can protect your data from accidental corruption.
  • Rather than defining the data in the form of public, we can declare those fields as private.
 public class School
{
 private string Schooldepartname;
 public string SchoolDepartname
 {
  get
  {
   return Schooldepartname;
  }
  set
  {
   Schooldepartname =value;
  }
 }
}
public class Departmentmain
{
 public static int Main(string[] args)
 {
  School d= new School();
  d.SchoolDepartname="Communication";
  Console.WriteLine("The Dept. Name is :{0}",d.SchoolDepartname);
  return 0;
 }
}

Output:
The Dept. Name is : Communication

Benefits of Encapsulation :

  • In Encapsulation fields of a class can be read-only or can be write-only.
  • A class can have control over in its fields.
  • A class can change data type of its fields anytime but users of this class do not need to change any code.
From the above we can see the use of Encapsulation by using properties. The property has two accessor get and set. The get accessor returns the value of the some property field. The set accessor sets the value of the some property field with the contents of "value". Properties can be made read-only. This is accomplished by having only a get accessor in the property implementation.

  • Abstraction refers to the act of representing essential features without including the background details or explanations.
  • Abstraction defines way to abstract or hide your data and members from outside world.
  • Classes use the concept of abstraction and are defined as a list of abstract attributes.
  • Simply speaking Abstraction is hiding the complexities of your class or struct or in a generic term Type from outer world.
  • This is achieved by means of access specifiers.
Access Modifier Description (who can access)
Private Only members within the same type.  (default for type members)
ProtectedOnly derived types or members of the same type.
Internal Only code within the same assembly. Can also be code external to object as long as it is in the same assembly.  (default for types)
Protected internal Either code from derived type or code in the same assembly. Combination of protected OR internal.
Public Any code. No inheritance, external type, or external assembly restrictions.


namespace AbstractionExample
{
public abstract class Shape
        {
            private float _area;
            private float _perimeter;

            public float Area
            {
                get
                {
                    return _area;
                }
                set
                {
                    _area = value;
                }
            }
            public float Perimeter
            {
                get
                {
                    return _perimeter;
                }
                set
                {
                    _perimeter = value;
                }
            }
            public abstract void CalculateArea();
            public abstract void CalculatePerimeter();
        }
}


Advantages of abstraction are the hiding of implementation details, component reuse, extensibility, and testability. When we hide implementation details, we reveal a cleaner, more comprehensible and usable interface to our users. We are separating our interface from our implementation, and this makes component reuse more practical.

Tuesday, December 18, 2012

Properties and Indexers

Properties, How it is different from variable fields. 

Properties are a natural extension to fields.
Unlike a variable, a property is not stored in a memory location.
It is made up of functions. Thus even though a property and a field share the same syntax a property has the advantage that code gets called.
When we initialize a variable, no code in our class gets called.
We are not able to execute any code for a variable access or initialization at all. In the case of a property, we can execute tons of code.
This is one singular reason for the popularity  and the use of properties.
i.e. One simple example is setting the value of a variable. If it is through a variable, we have no control over the value used. If the same access is through a property, the programmer has no inkling of whether it is a property or a variable, we can build range checks to make sure that the variable does not cross certain bounds.

public class zzz
{
public static void Main()
{
aa a = new aa();
int gg = a.ff + 9;
System.Console.WriteLine(gg);
}
}
public class aa
{
            public int ff {
            get
            {
            System.Console.WriteLine(“in get”);
           
            return 12;
            }
            }
}

Output
in get
21

A property should have at least one accessor, in our case, a get as we want to read the value of the property. Thus a.ff calls the get accessor which returns an int, in this case 12. If we did not have access to the code of the class aa, we would have assumed ff to have been a variable.

a.cs
public class zzz
{
public static void Main()
{
aa a = new aa();
a.ff = 19;
System.Console.WriteLine(a.ff);
}
}
public class aa
{
public int ff {
            get
            {
            System.Console.WriteLine(“in get”);
            return 12;
            }
            set
            {
            System.Console.WriteLine(value);
            }
}
}

Output
19
in get
12

The reason we use a property and not a variable is because if we change the value of a variable/field,  then code in our class is not aware of the change. Also we have no control over what values the variable will contain. The user can change them to whatever he/she likes and we cannot implement range checks on the variable. Also the user may want to associate some action with the changes in the value of the variable. Using a property, reading or writing to the variable also can be monitored.

a.cs
public class zzz
{
public static void Main()
{
aa a = new aa();
a.ff = 19;
System.Console.WriteLine(a.ff);
}
}
public class aa
{
int f1;
public int ff {
            get
            {
            System.Console.WriteLine(“in get”);
            return f1;
            }
}
}

Compiler Error
a.cs(6,1): error CS0200: Property or indexer ‘aa.ff’ cannot be assigned to — it is read only

You are allowed to declare a property readonly by omitting the set accessor. No one is now allowed to change the value of the property. It now behaves as a const or readonly field.

Indexers

An indexer lets us access members of a class as if it were an array.

a.cs
public class zzz
{
public static void Main()
{
yyy a = new yyy();
a[1] = 10;
}
}
public class yyy {
}
Compiler Error
a.cs(6,1): error CS0021: Cannot apply indexing with [] to an expression of type ‘yyy’

We have created an object a that looks like yyy. The object a, in no sense of the word is an array. We are assuming that a is an array and we’ve used the array syntax a[], hence it gives us an error.

a.cs
public class zzz
{
public static void Main()
{
yyy a = new yyy();
a[1] = 10;
}
}
public class yyy
{
public int this[int i]
{
set {
      System.Console.WriteLine(“in get “ + value + “ “ + i);
}
}
}

Output
in get 10 1
 
Indexers

An indexer lets us access members of a class as if it were an array.

a.cs
public class zzz
{
public static void Main()
{
yyy a = new yyy();
a[1] = 10;
}
}
public class yyy {
}
Compiler Error
a.cs(6,1): error CS0021: Cannot apply indexing with [] to an expression of type ‘yyy’

We have created an object a that looks like yyy. The object a, in no sense of the word is an array. We are assuming that a is an array and we’ve used the array syntax a[], hence it gives us an error.

a.cs
public class zzz
{
public static void Main()
{
yyy a = new yyy();
a[1] = 10;
}
}
public class yyy
{
public int this[int i]
{
set {
      System.Console.WriteLine(“in get “ + value + “ “ + i);
}
}
}

Output
in get 10 1

Saturday, December 15, 2012

Method Overriding

The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.

In this example, the class Square must provide an overridden implementation of Area because Area is inherited from the abstract ShapesClass:


abstract class ShapesClass
{
    abstract public int Area();
}

class Square : ShapesClass
{
    int x, y;
    // Because ShapesClass.Area is abstract, failing to override
    // the Area method would result in a compilation error.
    public override int Area()
    {
        return x * y;
    }
}

Points to remember : 
An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method. 
You cannot override a non-virtual or static method. The overridden base method must be virtualabstract, or override.
An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.
You cannot use the modifiers newstaticvirtual, or abstract to modify an override method.
An overriding property declaration must specify the exact same access modifier, type, and name as the inherited property, and the overridden property must be virtualabstract, or override.
The override, virtual, and new keywords can also be applied to properties, indexers, and events.

Friday, December 14, 2012

C# XML Document , XPath Query

Select XML Nodes by Name

To find nodes in an XML file you can use XPath expressions. Method XmlNode.Selec­tNodes returns a list of nodes selected by the XPath string. Method XmlNode.Selec­tSingleNode finds the first node that matches the XPath string.
Suppose we have this XML file.

[XML]
<Names>
    <Name>
        <FirstName>John</FirstName>
        <LastName>Smith</LastName>
    </Name>
    <Name>
        <FirstName>James</FirstName>
        <LastName>White</LastName>
    </Name></Names>

To get all <Name> nodes use XPath expression /Names/Name. The first slash means that the <Names> node must be a root node. SelectNodes method returns collection XmlNodeList which will contain the <Name> nodes. To get value of sub node <FirstName> you can simply index XmlNode with the node name: xmlNode["FirstName"].InnerText. See the example below.

[C#]
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
  string firstName = xn["FirstName"].InnerText;
  string lastName = xn["LastName"].InnerText;
  Console.WriteLine("Name: {0} {1}", firstName, lastName);
}

The output is:
Name: John Smith
Name: James White

Select XML Nodes by Attribute Value

This example shows how to select nodes from XML document by attribute value. Use method XmlNode.Selec­tNodes to get list of nodes selected by the XPath expression. Suppose we have this XML file.

[XML]
<Names>
    <Name type="M">John</Name>
    <Name type="F">Susan</Name>
    <Name type="M">David</Name>
</Names>

To get all name nodes use XPath expression /Names/Name. To get only male names (to select all nodes with specific XML attribute) use XPath expression /Names/Name[@type='M'].

[C#]
XmlDocument xml = new XmlDocument();
xml.LoadXml(str);  // suppose that str string contains "<Names>...</Names>"XmlNodeList xnList = xml.SelectNodes("/Names/Name[@type='M']");
foreach (XmlNode xn in xnList)
{
  Console.WriteLine(xn.InnerText);
}

The output is:
John
David

Select Top XML Nodes using XPath

This example shows how to select Top N nodes of the specific name from an XML document. To select nodes from XML use method XmlNode.Selec­tNodes. Pass XPath expression as a parameter and the method returns a list of selected nodes. Suppose we have this XML file.

[XML]
<Names>
    <Name>James</Name>
    <Name>John</Name>
    <Name>Robert</Name>
    <Name>Michael</Name>
    <Name>William</Name>
    <Name>David</Name>
    <Name>Richard</Name>
</Names>
To get all <Name> nodes use XPath expression /Names/Name. If you don't want to selected all nodes, but only top 5 nodes, you can uses XPath expression like this /Names/Name[position() <= 5]. See the example below.

[C#]
XmlDocument xml = new XmlDocument();
xml.LoadXml(str);  // suppose that str string contains "<Names>...</Names>"XmlNodeList xnList = xml.SelectNodes("/Names/Name[position() <= 5]");
foreach (XmlNode xn in xnList)
{
  Console.WriteLine(xn.InnerText);
}

The output is:
James
John
Robert
Michael
William

Thursday, December 13, 2012

Array in C#

Arrrays in Csharp

Arrays in csharp:
            Arrays provide the same functionality and they work similarly to how the arrays work in other programming languages. However, there are few things which you might keep in mind while working with arrays. This article explains about the different types of arrays, their methods and how to work with them.
Arrays in c# are not dynamic in size, they are fixed in size. Arrays are zero indexed, that is array index starts at zero and the total number of elements in an array is n-1. An array is represented by a single variable name. The individual elements are accessed using the variable name together with one or more indexes between. For example consider an instance where you need to display the list of products available at an Electronic Gadgets Store. One can use any one of the following syntax to accomplish this task.
Array Syntax:
string[ ] products;
products = new string[3];
products[0] = "Griffin iTrip FM Transmitter”;
products[1] = "Griffin DJ Cable";
products[1] = "USB Power Adapter";
Or
You can specific the length of the array at the time of variable declaration.
string[ ] products = new string[3];
products[0] = "Griffin iTrip FM Transmitter”;
products[1] = "Griffin DJ Cable";
products[1] = "USB Power Adapter";
Or
Entire Declaration at same time
string[ ] products = new string[ 3]  { " Griffin iTrip FM Transmitter”, " Griffin DJ Cable ", " USB Power Adapter " };
 Or
 You can also omit the size and new operator as shown:
 string[ ] products = new string[ ] { " Griffin iTrip FM Transmitter”, " Griffin DJ Cable ", " USB Power Adapter " };
string[ ] products = { " Griffin iTrip FM Transmitter”, " Griffin DJ Cable ", " USB Power Adapter " };

 Multi Dimension Arrays:
Multi Dimension Arrays are of two types Rectangular Arrays and Jagged Arrays.
Rectangular Arrays are arrays in which all the sub arrays in a particular dimension have same length. In our example we can use Multi Dimension Arrays to add some information for the products like Product ID and product code.
string[,] productattributes = new string[3,3] { { "GIFT", "Griffin iTrip FM Transmitter", "$42" }, 
{ "GDC", "Griffin DJ Cable", "$67" }, { "UPA", "USB Power Adapter", "$76" } };
 All the syntax declarations which are used for the single dimension array can be used for the multi dimension arrays.
 Similarly we can increase the dimension of the array to make it as three dimension. By using these three dimension array we categorize the products. The syntax for the three dimension array goes here.
Syntax:
string [, ,] productcateogries = new string[3, 1, 4]
{{{“Car Accessories", "GIFT", "Griffin iTrip FM Transmitter", "$42" } },
  {{“Cables & Docks", "GDC", "Griffin DJ Cable", "$67”}},
  {{“Power Accessories", "UPA", "USB Power Adapter", "$76”}}};

string [ ] products = new string [3] string [ products ];
string [ ] productattributes = new string[3, 3];  string [ attributes, products];
string [ ]productcateogires = new string[3,1,4];  string [categories, products, attributes];
                   

Jagged Arrays:     
                                    Jagged Arrays are arrays within arrays. Jagged Arrays can have sub-arrays with different lengths. One can combine ‘n’ number of arrays with same dimensions which may have same length or different length.                     
Continuing with our products example we can combine ‘productscategories’ Array and ‘customerorder’ array by using a jagged array and the syntax is as follows:
string[,] customers = new string[3, 3] { { "GIFT", "Johny", "$42" }, { "GDC", "Mike", "$45" }, { "GDC", "Robin", "$24" } };

string [ ][,]customerorder = new string[2][,]{productattributes, customers};

Retrieving information from arrays:                       
                        We can retrieve the information from the arrays by using the indexes. One can a for loop or foreach loop to retrieve information from the arrays.

Using for loop:
For example you can access the array information by using the following syntax:
string productcategory  = Productscategories[2,0,0];
string productattributes = productattribute[1,0];
Now by using for loop we can iterate through all the elements in the array as shown below:
For Loop for one dimensional array:
for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("{0}",products[i]);
            }

For loop for two dimensional array:
  for( int i=0;i<3;i++)
            {
                for (int j = 0; j <3; j++)
                {
                    Console.WriteLine("{0}", productattributes[i, j]);
                }
                Console.WriteLine("================");
            }

For loop for three dimensional array:
for (int i = 0; i <2; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    for (int k = 0; k < 3; k++)
                    {
                        Console.WriteLine("{0}", customerorder[i][j, k]);
                    }
                    Console.WriteLine("================");
                }
            }
Instead of specifying the length of the array we can use the array.getlength() method as follows:

productattributes.GetLength (0) or productattributes (1) which returns the length of the arrays.

Using foreach loop:

To be more efficient in order to iterate through the collections, C# provides us with the foreach loop. With only one single line of code u can iterate through all the elements in the productattributes or productcateogries or customerorder. Foreach loop can be used as follows:

foreach(string s in productattributes)
            {
                Console.WriteLine("{0}", s);
            }
and
foreach(string s in productcateogries)
            {
                Console.WriteLine("{0}", s);
            }
and
foreach(string s in customerorder[0])
            {
                Console.WriteLine("{0}", s);
            }

For More Details :
For all the methods and properties of the arrays you can visit the following link:
Most of the methods specified will work only for the single dimensional arrays and not for the multi-dimensional and jagged arrays.