Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

ISAPI (Internet Server Application Programming Interface) filter

Internet Server Application Programming Interface (ISAPI) is an API developed to provide the application developers with a powerful way to extend the functionality of Internet Information Server (IIS). ISAPI filters always run on an IIS server, filtering every request until they find one they need to process. The ability to examine and modify both incoming and outgoing streams of data makes ISAPI filters powerful and flexible.

Developing a CGI(Common Gateway Interface) program involves creating an EXE with C, C++, and/or Perl programming languages. This EXE file will be executed and terminated for every request received, causing an excessive memory usage, whenever users hit the same page over and over again!

This excessive memory usage that could bring the server completely down, has been solved under ISAPI extensions. An ISAPI extension is a regular DLL file that exposes 3 special functions that is called by the calling process (i.e., IIS) and therefore, will be loaded to memory once, no matter how many clients are going to use it at the same time.

Since the ISAPI extension and the calling process (IIS) live at the same address space, they could contact each other, directly. This means a great potential to bring the whole IIS down, and in some cases, the entire web server! Take a look at the following figure:

Both ISAPI filters and ISAPI extensions can only be developed using C/C++. Visual Studio comes with wizards that make ISAPI development fast and easy.

Uses of ISAPI filters

ISAPI filters can be registered with IIS to modify the behavior of a server. Filters can perform the following tasks:

Change request data (URLs or headers) sent by the client.
Control the user name and password used with anonymous or basic authentication.
Modify or analyze a request after authentication is complete.
Perform custom authentication.
Handle encryption and compression.

NOTE: ISAPI filters DLLs cannot be requested explicitly, like ISAPI extensions can.

References :
http://msdn.microsoft.com/en-us/library/ms524610.aspx
http://www.codeproject.com/KB/ISAPI/isapi_extensions.aspx


Globalization and Localization

Ms. Asha Bora has done some studies on Globalization and Localization.. Lets see what she has to say..

Globalization and localization are very important features of .Net framework, which is very useful and about which every programmer should be aware of while creating an application. If I want my application to be used by everyone then I have to make my interface in a language which everyone can understand or say in a global language. But at the same time it is not possible that everyone in the world knows a particular language. So, in order to make those people use the application, I have to publish it in their regional language or say in their local language, this is known as localization .

From the introduction of the article you must have understood the basic meaning of globalization and localization. Now let’s see a proper definition of it in terms of a programmer.

This very important feature is used by .Net to make our programs universal. Now if we talk in term of programming then GLOBALIZATION can be defined as the process of designing and developing an application that function for multiple cultures and regions, irrespective of the language and regional differences and LOCALIZATION is the process of customizing your application for a given culture and locale. It consists primarily of translating the user Interface according to a culture. Culture will decide date display settings (like, mm/dd/yyyy or dd/mm/yyyy), currency display formats etc.

Now, the process by which we can make sure that our program will be localized is known as Internationalization or Globalization. In simpler terms, Globalization can be defined as the set of activities which will ensure that our program will run in regions with different languages and cultures.

Thus, globalization is related to intrinsic (basic) code changes to support such changes we use Resource files etc. Whereas, localization is the process of using a particular culture and regional info so that the program uses the local languages and culture. This means translating strings into a particular local language. This covers putting language specific strings in the resource files. Globalization starts in the main construction phase along with the code development. Localization generally comes later.

Now let’s see how we define the culture and region code.

We all know that languages depend upon the geographical location. For example, French is spoken in France as well as in Canada (besides many other countries). But linguistically speaking, Canadian French is quite different from French spoken in France. Similarly, there are linguistic differences between US English and British English. Therefore, the language needs to be associated with the particular region where it is spoken, and this is done by using locale (language + location).

For example
: fr is the code for French language. fr-FR means French language in France. So, fr specifies only the language and FR specifies the region France whereas fr-FR is the locale. Similarly, fr-CA defines another locale implying French language and culture in Canada. If we use only fr, it implies a neutral culture (i.e., location neutral).

Now, in order to change the current culture, we have to change two properties of the CultureInfo class- UICulture and Culture.

ASP.NET can set the UICulture and Culture properties for the page to the language and culture values that are passed by the browser. Alternatively, you can set the UICulture and Culture properties explicitly, either declaratively or in code. You can also set the values declaratively in
Web.config file under the property and these two properties can be set using the overloaded constructor of the class and then we can use this class to change the culture of the currently executing program.

UICulture: gets/sets the user interface culture for the currently executing thread. This property helps the runtime to load the resource strings from a specific resource. This property can take neutral cultures as well as locales.
  • Thread.CurrentThread.CurrentUICulture = new CultureInfo(“fr”); OR
  • Thread.CurrentThread.CurrentUICulture = new CultureInfo(“fr-CA”);
Culture: gets/sets the region specific culture and formats of currency, dates etc. This needs language as well as location.
  • Thread.CurrentThread.CurrentCulture = new CultureInfo(“fr-CA”); // we have given locale
  • Thread.CurrentThread.CurrentCulture = new CultureInfo(“fr”); // wrong, will not work
In my next article I will talk about “How to implement Globalization in our application”.

References:

  • http://msdn.microsoft.com/en-us/library/ms227427.aspx
  • http://www.codeproject.com/Kb/aspnet/localizationByVivekTakur.aspx

Jagged Arrays

Our dear friend Ms.Asha Bora has done some studies on the wonderful Jagged Arrays..
Lets see what she has to say..

In this Article I will be discussing about Jagged Arrays. Many of us who are working as a Programmer may not be knowing about it, as I didn't knew it. One of my friends told me about Jagged Arrays. So I thought that I should explore myself on this topic so that people like me can know more about it..

.Net supports two types of Arrays:
Single dimensional arrays(Linear)
Multi-dimensional arrays - These are of two type : Rectangular Arrays and Jagged Arrays

What are Jagged Arrays?

A jagged Array is nothing but a multidimensional array, whose elements are arrays. The elements of an array can be of different dimensions and sizes. A jagged array is also known as “array of arrays”. Following is an example to show the declaration and initialization of jagged array:

i. Declaration : int[][] jaggedArray = new int[3][];
       Over here‘3’shows the number of rows in the array.

ii. Initialization: There are many ways to initialize a jagged array. In the given example each of the element is a single dimensional array.

jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[3];


We can also do initialization of the arrays without knowing its size.
For Example :

int[][] jaggedArray2 = new int[][]
{
   new int[] {1,3,5,7,9},
   new int[] {0,2,4,6},
   new int[] {11,22,33}
}
;

We can also do this in the below given way. Notice that we cannot omit the new operator from the elements initialization because there is no default initialization for the elements..

int[][] jaggedArray3 =
{
   new int[] {1,3,5,7,9},
   new int[] {0,2,4,6},
   new int[] {11,22,33}
};

NOTE: A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null. The length property of the array returns the number of arrays contained in the jagged array.

The following C# example will tell us how we can iterate in a jagged array.

class JaggedArray_Test
{
static void Main()
{
// Declare the array of two elements:
int[][] jaggedarr = new int[2][];

// Initialize the elements:
jaggedarr [0] = new int[5] { 3, 9, 15, 21, 27 };
jaggedarr [1] = new int[4] { 6, 12, 18, 24 };

// Display the array elements:
for (int i = 0; i < jaggedarr.Length; i++)
{
System.Console.Write("Element({0}): ", i);

for (int j = 0; j < jaggedarr [i].Length; j++)
{
System.Console.Write("{0}", jaggedarr [i][j]);
System.Console.Write(“ ”);
}
System.Console.WriteLine();
}
}
}
OUTPUT will be: Element(0) 3 9 15 21 27
Element(1) 6 12 18 24

Difference between multidimensional arrays (also known as rectangular arrays) and jagged arrays:

In a multi-dimensional array we have to declare both dimensions. Suppose we want to store the number of months and the days of each month in an array. If we create a multidimensional array then we have to give a fixed size to both the number of rows and column (To store the number of days for the month).But since each month has different number of days thus declaring the fixed size will lead to wastage of memory. Thus in this case we can use jagged arrays, as we don’t need to declare the second dimension of the array. It is enough to declare just the number of rows (to store number of months) in jagged array. The column or say the size of each linear array will vary as per the requirement.

THUS WE CAN SAY Jagged arrays have certain advantages over rectangular arrays. Jagged arrays are more space efficient, since not all rows (in a two-dimensional array) must have the same number of columns. In addition, since each row has its own one-dimensional array, we can easily pass an individual row to a method that requires a one-dimensional array parameter.
We will find working with jagged arrays much easier if you keep in mind that a jagged array is really an array of arrays.

References :
 http://msdn.microsoft.com/en-us/library/2s05feca(VS.80).aspx
 http://www.odetocode.com/Articles/253.aspx
 http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=128


LINQ : An Introduction

In this article, we will be discussing a very useful Microsoft technology called LINQ..which was introduced with .Net 3.0.

So, Lets see what LINQ is..

LINQ stands for Language Integrated Query. It is Microsoft’s new technology for powerful and easy general purpose data access in a type-safe way.

Now the question arises : What was the need to develop LINQ ??

Well.. the problem was that.. Traditionally, our data source used to determine our selection of a low-level data access API. For example, to fetch relational data from a database table, we would use ADO.NET, to parse XML data, we might use some combination of XPath and XML DOM APIs. Each data access API requires its own specialized syntax (SQL queries, as an example), and typically forces us..the developers to shuffle data between their business objects and the data access API.

All of the diverse data access strategies and APIs means there is a tremendous amount of mental energy expended to build the basic data features needed in every business application. LINQ helps us to eliminate this mental overhead.

Basically, It defines a set of standard query operators in the System.Linq namespace to select, filter, aggregate, and partition data from any type that implements the IEnumerable or IEnumerable <T> interfaces. The standard query operators are compliant with the Common Language Specification (CLS) and work inside any .NET language that supports generics. LINQ gives .Net developers the ability to query and transform data using any .Net Language of their choice.

LINQ is very similar to SQL. So, if you are used to using SQL to query databases, you are going to have something of a head start with LINQ.

This means that whether the data lives in XML, or database, or some collection of objects, we can run through the desired data in a common way..by simply writing SQL like queries.. Query expressions, like “from”, “where”, and “select”, “order by” and all the others you know and love from SQL can now be used in C# and VB .Net.

Lets now jump on to our first code and see how does LINQ code looks like..

In the following C# code, we are using LINQ to query a collection of Strings.

string[] flowers = { "Rose", "Lotus", "Jasmine", "Lily" };
IEnumerable query = from n in flowers
           where n.Length == 4
           orderby n descending
           select n;
foreach (string flower in query)
{
   Console.WriteLine(flower);
}

Inside this code is a LINQ query expression. The code will print out all the flower names in descending alphabetical order. We will discuss on the LINQ syntax in our future article.

The next query produces the same results, but queries data inside an XML fragment.

XElement flowers = XElement.Parse(
        @"<flowers>
           <flowers>Rose</flowers>
           <flowers>Lotus</flowers>
           <flowers>Jasmine</flowers>
          <flowers>Lily</flowers>
         </flowers>"
        );


IEnumerable query = from n in flowers.Elements("flowers")
          where n.Value.Length == 4
          orderby n.Value descending
          select n.Value;
foreach (string flower in query)
{
   Console.WriteLine(flower);
}

Although we made some slight changes to dig into the XML, the operators inside the query expression remains the same. LINQ query expressions are similar to SQL SELECT commands with FROM, WHERE, ORDERBY, GROUP, AND SELECT clauses.

Microsoft also designed LINQ to integrate closely with .NET languages and their environment. When typing the above queries, Visual Studio provides Intellisense for auto-completion. The compiler can perform syntax and type checking on query expressions.

Thus, we discussed the use of LINQ and what LINQ is.. We also saw an example of implementation of LINQ. We will be carrying on with the LINQ in our coming articles..

References :

http://msdn.microsoft.com/
• http://www.odetocode.com/
• http://www.programmersheaven.com/
• http://blogs.msdn.com/cyrusn/



String Equality and Interning

In the previous article on “Strings : Java and C#”, I had discussed the concept of strings, and some common functions for string manipulation. This time, I will be mainly talking on string equality, and about string interning.

So, Lets start with string equality first.. But before starting, keep in mind.. that java or C#.. Strings are nothing but references.

Now.. Because of the transparent optimizations performed by runtime, its very necessary to know when 2 strings are equal. Strings can be compared by comparing string instances, object instances, and their values. The default comparison operations in both C# and Java compare the string's values instead of the object references.

Lets try to understand this by the following C# program.

using System;

public class StringTest
{


public static void Main(string[] args)
{

char[] c = new char[] {'H','e','l','l','o'};
string[] strings = new string[4];
strings[0] = "Hello";
strings[1] = "World";
strings[2] = "Hello";
strings[3] = new string(c);

Console.WriteLine("-----[ Comparing strings using ==
operator of System.String ]-----");
for (int i =0; i < strings.Length; ++i){
for (int j = i+1; j < strings.Length; ++j){

Console.WriteLine("{0} = {1} {2}",i,j,strings[i] ==
strings[j]);
}
}


Console.WriteLine("-----[ Comparing strings using ==
operator of System.Object ]-----");
for (int i =0; i < strings.Length; ++i){
for (int j = i+1; j < strings.Length; ++j){

Console.WriteLine("{0} = {1}{2}",i,j,
(object)strings[i] ==
(object)strings[j]);
}
}


Console.WriteLine("-----[ Comparing String using the Equals
method ]-----");
for (int i =0; i < strings.Length; ++i){
for (int j = i+1; j < strings.Length; ++j){

Console.WriteLine("{0} = {1}{2}",i,j,
strings[i].Equals(strings[j]));
}
}
}
}

The output of above code is :

-----[ Comparing strings using == operator of System.String ]-----
0 = 1 False
0 = 2 True
0 = 3 True
1 = 2 False
1 = 3 False
2 = 3 True
-----[ Comparing strings using == operator of System.Object ]-----
0 = 1False
0 = 2True
0 = 3False
1 = 2False
1 = 3False
2 = 3False
-----[ Comparing String using the Equals method ]-----
0 = 1False
0 = 2True
0 = 3True
1 = 2False
1 = 3False
2 = 3True

In C#, the == operator of the System.Object method compares the references of the objects and returns true if the two references point to the same object, and false otherwise. The == operator is overloaded in the System.String class to compare the value of the strings instead of the actual objects they refer to. Therefore, in example above, strings[3] == strings[0] returns true because they have the same string value. However, when both strings[0] and strings[3] are cast to the object and then compared using the == operator, they return false. This is because strings[3] points to a different string object.

C# also has the Equals method, which is similar in behavior to the == operator. Notice in the output of above code that comparing strings using the Equals method and the overloaded == operator gives the same results.

Java programmers must be particularly careful when dealing with the == operator and C# strings.

Note that in Java the equals method functions the same way as the == operator of C#. The equals method is defined on java.lang.Object, and by default it compares the object references. However, the java.lang.String class overrides the equals method and compares the String values.

Coming to string interning now..

String Interning is a method of storing only one copy of each distinct string value, which must be immutable.
Simply stated: string interning keeps a hashtable of strings while running an application. If a string with the same contents is created, no new heap allocation happens but instead a reference to the existing (identical) string is returned.

String interning is supported by most of the modern object-oriented programming languages, including Python, Ruby (with its symbols), Java and .NET languages.

The single copy of each string is called its 'intern' and is typically looked up by a method of the string class, for example String.intern() in Java, and in C# as well.

String equality and interning is very much related to each other.. Lets see how..

Both Java and C# support String interning, so both the JVM and the CLR create only one object from a String that has the same value. This is an optimization feature so that different String references pointing to the same literal value are internally stored as pointing to the same String object. Interning saves RAM at the expense of more CPU time to detect and replace duplicate Strings. There is only one copy of each String that has been interned, no matter how many references point to it. Because Strings are immutable, the intern process is free to further save space, for example, by not creating a separate String literal for "yoddha" when it exists as a substring of some other literal such as "tech yoddha". It also speeds up the String equality compares. Interned Strings will compare faster even if you use equals instead of ==.

The intern Gotcha

All String literals present at compile time are automatically interned. It is only Strings generated on the fly as the program runs that might not be interned. A nasty side effect of this behaviour is that a program will work fine for some simple cases, but fail on complex ones. The problem comes if you used == to test for String equality where you should have used equals. The wrong code will still work much of the time because most String literals are naturally interned.

Manual Interning

It can be implemented by using intern() method. But its not advised to try and implement interning manually.. The big problem with intern is once you intern a String, you are stuck with it in RAM until the program ends. It is no longer eligible for garbage collection, even if there are no more references to it. If you want a temporary interned String, you might consider interning manually.

However, in the most recent JVMs, the interned string cache is now usually implemented in soft references fashion, so that interned strings may become eligible for garbage collection as soon as they are no longer strongly referenced.

Further References :

• http://book.javanb.com/NET-For-Java-Developers-Migrating-To-Csharp/ 0672324024_ch12lev1sec2.html


• http://mindprod.com/jgloss/interned.html


• http://javatechniques.com/



Strings : Java and C#

In this article, I would be discussing with you the concept of strings.. and what does modern programming languages like Java and C# have in store for String manipulation.

Let's first start with understanding “what is a String".

A string is basically a sequence or a string of Unicode characters. It is one of the most common data types that a programmer deals with. Input validation, text analysis and file conversions are several direct applications of string manipulation.

In some languages such as C, strings are treated as character arrays. Whereas, Java and C#, works with complete strings and treat them as objects.

Let’s now move on to discuss the implementation of strings in java and C#.

Strings in Java :

For string manipulation in java, in java.lang package we have a class called String which extends Object class. String objects are created so as to store character sequences. It may contain null as well.

String Class is immutable, i.e. Strings in java, once created and initialized, cannot be changed on the same reference. A java.lang.String class is final which implies no class can extend it. The java.lang.String class differs from other classes. One difference being that the String objects can be used with the += and + operators for concatenation.

A simple String can be created using a string literal enclosed inside double quotes as shown :

String str = "Tech Yoddha";

Or by passing some characters to the constructor like this :

String str = new String("Tech Toddha");

Since a string literal is a reference, it can be manipulated like any other String reference. The reference value of a string literal can be assigned to another String reference.

If 2 or more Strings have the same set of characters in the same sequence then they share the same reference in memory. Such strings are said to be interned, meaning that they share a unique String object. The String class maintains a private pool where such strings are interned.

I will be discussing more on String Interning in my upcoming article. As of now, lets continue with String creation..

Constructing String objects can also be done from arrays of bytes, arrays of characters, or string buffers. A simple way to convert any primitive value to its string representation is by concatenating it with the empty string (""), using the string concatenation operator (+).

String class contains many useful methods for string manipulation. Lets see some of the them :

boolean equals(Object obj) and boolean equalsIgnoreCase(String str) : The comparison using equals() is case-sensitive. To perform a comparison that ignores case differences, call equalsIgnoreCase( ).

Example:

String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> “+s1.equalsIgnoreCase(s4));

• int length() : This function returns an int which is the number of characters present in a String variable.

Example:

String str = "Tech yoddha";
System.out.println("Length : "+str.length);
//output : 11

• int compareTo(String str) and int compareToIgnoreCase(String str) : This method is used to compare two strings.
It returns 0 if both strings are same,
It returns a negative value if first string is less than the second string and
It returns a positive value if first string is greater than the second string.

Example:

String smaller = "abc";
String greater = "bcd";
If(greater.compareTo(smaller) >0)
System.out.println(greater+" is greater than "+smaller);
else
System.out.println(greater+" is lesser than "+smaller);
// output: bcd is greater than abc

• String replace(char oldChar, char newChar) : This method is used to replace a character with another character throughout the string.

Example:


String s1 = "java" , s2 ;
s2=s1.replace('a','#');
Now a in java is replaced by #. So s2 is referring to j#v#.

• boolean startsWith(String prefix) and boolean endsWith(String suffix) : These two methods are used to check respectively whether the string starts with or ends with a particular character combination.

• String trim() : This method is used to remove leading and trailing spaces from a string object.

There are lot more functions in String class for string manipulation like indexOf(), split(), substring(), toUpperCase(), toLowerCase(), charAt() etc.

You can also use StringBuilder and StringBuffer classes for manipulating strings.

Strings in C# :


C# or Java, the basic concept of string remains the same.

Like Java, in C# also, the string type represents a string of Unicode characters. Here, we have System.String class which we can use for string manipulation.

Lets discuss over String class in C# now.

But before that, I want to tell you something about string and String in C#. Many people think that string with a small 's' is different than String with capital 'S'. But actually string is an alias for System.String in the .NET Framework. That means string is same as String.
So, keep in mind that whether you write string or String, to C# compiler both means the same.

Lets continue with class String now..

The methods and features of System.String is similar to java.lang.String, but there are a few different things here.

In C#, Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive.

The + operator concatenates strings like this :

string a = "good " + "morning";

The [] operator accesses individual characters of a string:

char x = "test"[2]; // x = 's';

String literals are of type string and can be written in two forms, quoted and @-quoted.

Quoted string literals are enclosed in double quotation marks ("):
"good morning" // a string literal

@-quoted string literals start with @ and are enclosed in double quotation marks. For example:
@"good morning" // a string literal

The advantage of @-quoting is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:
@"c:\Docs\Source\a.txt"
// rather than "c:\\Docs\\Source\\a.txt"

To include a double quotation mark in an @-quoted string, double it:
@"""Ahoy!"" cried the captain." // "Ahoy!" cried the captain.

You may try this example :

// keyword_string.cs
using System;
class test
{
public static void Main( String[] args )
{
string a = "\u0068ello "; // \u0068 is the unicode
representation for letter “h”.

string b = "world";
Console.WriteLine( a + b );
Console.WriteLine( a + b == "hello world" );
}
}

Rest all the functions are more or less same as that in java.lang.String class.

Thus, we learnt the basic concept of Strings.. and how they are implemented in C# and java.. and also discussed a few places where C# String class varies from java String class.

References :
  • http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html
  • http://msdn.microsoft.com/en-us/library/362314fe.aspx
  • http://www.java2s.com/Tutorial/Java/0040__Data-Type/equalsandequalsIgnoreCase.htm

Garbage Collection

Welcome again readers!! Now our authors are back from the examination-season, and here Ms. Asha Bora presents an insight on Garbage collection in C# or rather in .NET Framework.

In C#, we can never destroy an object our selves. But, ever we thought why the C# designer’s did not give us this “RIGHT”? There are many good reasons for this .

Suppose we have given the responsibility to destroy an object then, there are chances that:
· We’d forget to destroy the object: then the object destructor would not run, leading to memory crises.
· We’d try to destroy an Active object, but what if suppose a class held a reference to this active object???.....then it would be a problematic situation.
· We’d try to destroy the same object more than once, but this can be disastrous, depending on the destructor’s code.
These problems are unacceptable in C#. Thus garbage collector is responsible for destroying the object.


Therefore, Garbage Collection is a process which automatically frees the memory of an object. It is a service which is provided by one of the most essential component of .NET Framework known as CLR(Common Language Runtime).
It occurs when an object is no longer needed, but it’s not necessary that it occurs immediately .Then runtime collects the garbage only when required i.e. when memory crises occur (low memory) and at that time it does as much as it can.

The garbage collection guarantees the followings:
· Each object will be destroyed and its destructor will run. When a program ends, all outstanding objects will be destroyed.
· Each object is destroyed only when it becomes unreachable i.e. when no reference refers to the object.
· Each object is destroyed only once.

Conclusion: thus we can say that garbage collection (GC) is tremendously useful and it frees the programmer from the tedious house keeping chores that are easy to get wrong and allow the programmer to concentrate on the logic of the program.

Inheritence in C#

Multiple inheritence is not supproted by C#. But there is a solution to this using interfaces. Lets see how as explained by Ms. Asha Bora.

We know inheriting from a class is a powerful mechanism, but the real power of inheritance comes from inheriting from an interface.
Interface allows you to truly separate the "what" from "how". The interface tells what the name is, return type and parameter of the method are. Exactly how the method is implemented is not a concern of the interface. It represent how you want an object to be represent rather then how it happens to be implemented in a particular moment.

Syntax to declare interface: To declare the interface we use the interface keyword.
Eg:
interface IComparable
{
int xyz();
}


Points to be noted about Interface:
  • Interface should not contain any variable.
  • Interface should not have any constructor. Since a constructor contains the statements to initialize the variable of an object, but interface does not contain any variable.
  • A Destructor is also not allowed in an interface. Since it contain the statement to destroy the object instance.
  • No need to supply the access specifier to the methods. Since all the methods are public by default in an interface.
  • We cannot nest any types like enums , class, structs, interfaces, delegates inside an interface.
  • A class which implements an interface needs to implements all the members of the interface.

A class can inherit from a single class but can implement from multiple interfaces. An interface can inherit multiple interfaces. So we say that in C# multiple inheritance is applicable only through Interfaces, but not via classes.
A class or structure that implements an interface also implements the base interface of its inherited interface.
A class can extend another class and implement an interface at the same time. The base class is named first followed by a comma, followed by the interface.
eg:
class Defaultclass
{

}
class XYZ: Defaultclass, IComparable
{
...
}


Inheriting interface: we have declared an interface in the above example called IComparable, the below examples shows how a interface inherit another interface…
interface IOrder : IComparable
{
void abc();
}

Params Array in C#

Worried about Overloading a method due to unpredictable inputs!!
Here is a solution to this provided by C# and explained by Ms. Asha Bora.

Param arrays are very useful if you want to write methods that can take variable numbers of arguments, possibly of different types as parameter. If any one is familiar with OOPS then, he must be grinding his teeth in frustration at this sentence…Since in OOPS you use overloaded methods for this problem.

Overloading is the technical term for declaring two or more methods with the same name in the same scope. Overloading handles a situation where type and number of parameters vary. Where as param array can handle the situation if the types of parameter do not vary. While declaring a method suppose you are not sure about the number of arguments passed as a parameter, then we can use the param array.

How to declare Params array:
class A
{
public static int Array_Min(params int [] paramList)
{
//code
}
}


The effect of params keyword is that it allows you to call it by using any number of integer arguments. For example to find the minimum of 2 integer values, we would write it as:
int min=A.Array_Min(1,2);

The compiler translates this call into code similar to this:
int []array=new int[2];
array [0]=1;
array [1]=2;
int min=A.Array_Min(array);
similarly to find the minimum of 3 integer values,we would write the code as: int min=A.Array_Min(1,2,3);


Points to be noted about params arrays:
· You can use params keyword on only one dimensional arrays.
· You can’t overload a method based solely on the params keyword. The params keyword does not form part if a method’s signature, for example:
//compile time error: duplication declaration
public static int Min(int[]paramList)…
public static int Min(params int[]paramList)…
· You are not allowed ref or out params arrays, for example:
//compile-time errors
Public static int Min(ref params int[]paramList)…
Public static int Min(out params int[]paramList)…
· A params array must be the last parameter i.e. You can have only one params array per method.

A params int array is very useful since it allows any number of int arguments in a method call. you can use a param object array to declare a method that accepts any number of arguments of objects, allowing the arguments to be passed of any type.
· you can even pass it no arguments at all,
· you can also call it by passing the null as the argument,
· you can pass it an actual array ,
· you can pass any other arguments of different types and these arguments will automatically be wrapped inside an object array.