Saturday, March 24, 2012

Asp.Net 4.0 Features

Asp.Net 4.0 Features Changes :

01- ControlRenderingCompatabilityVersion Setting in the Web.config File
ASP.NET controls have been modified in the .NET Framework version 4 in order to let you specify more precisely how they render markup.

02- ClientIDMode Changes
The ClientIDMode setting in ASP.NET 4 lets you specify how ASP.NET generates the id attribute for HTML elements. In previous versions of ASP.NET, the default behavior was equivalent to the AutoID setting of ClientIDMode. However, the default setting is now Predictable.

03- HtmlEncode and UrlEncode Now Encode Single Quotation Marks
In ASP.NET 4, the HtmlEncode and UrlEncode methods of the HttpUtility and HttpServerUtility classes have been updated to encode the single quotation mark character (‘).

04- ASP.NET Page (.aspx) Parser is Stricter
The page parser for ASP.NET pages (.aspx files) and user controls (.ascx files) is stricter in ASP.NET 4 and will reject more instances of invalid markup.

05- Browser Definition Files Updated
The browser definition files have been updated to include information about new and updated browsers and devices. Older browsers and devices such as Netscape Navigator have been removed, and newer browsers and devices such as Google Chrome and Apple iPhone have been added.

06- System.Web.Mobile.dll Removed from Root Web Configuration File
In previous versions of ASP.NET, a reference to the System.Web.Mobile.dll assembly was included in the root Web.config file in the assemblies section under . In order to improve performance, the reference to this assembly was removed.

07- ASP.NET Request Validation
The request validation feature in ASP.NET provides a certain level of default protection against cross-site scripting (XSS) attacks. In previous versions of ASP.NET, request validation was enabled by default. However, it applied only to ASP.NET pages (.aspx files and their class files) and only when those pages were executing.
In ASP.NET 4, by default, request validation is enabled for all requests, because it is enabled before the BeginRequest phase of an HTTP request. As a result, request validation applies to requests for all ASP.NET resources, not just .aspx page requests.

08- Default Hashing Algorithm Is Now HMACSHA256
ASP.NET uses both encryption and hashing algorithms to help secure data such as forms authentication cookies and view state. By default, ASP.NET 4 now uses the HMACSHA256 algorithm for hash operations on cookies and view state. Earlier versions of ASP.NET used the older HMACSHA1 algorithm.

09- Configuration Errors Related to New ASP.NET 4 Root Configuration
The root configuration files (the machine.config file and the root Web.config file) for the .NET Framework 4 (and therefore ASP.NET 4) have been updated to include most of the boilerplate configuration information that in ASP.NET 3.5 was found in the application Web.config files. Because of the complexity of the managed IIS 7 and IIS 7.5 configuration systems, running ASP.NET 3.5 applications under ASP.NET 4 and under IIS 7 and IIS 7.5 can result in either ASP.NET or IIS configuration errors

10- ASP.NET 4 Child Applications Fail to Start When Under ASP.NET 2.0 or ASP.NET 3.5 Applications
ASP.NET 4 applications that are configured as children of applications that run earlier versions of ASP.NET might fail to start because of configuration or compilation errors.

11- ASP.NET 4 Web Sites Fail to Start on Computers Where SharePoint Is Installed
Web servers that run SharePoint have a Web.config file that is deployed at the root of a SharePoint Web site (for example, c:\inetpub\wwwroot\web.config for Default Web Site). In this Web.config file, SharePoint sets a custom partial-trust level named WSS_Minimal.
If you try to run an ASP.NET 4 Web site that is deployed as a child of this type of SharePoint Web site, you will see the following error: Could not find permission set named ‘ASP.Net’.

12- The HttpRequest.FilePath Property No Longer Includes PathInfo Values
Previous versions of ASP.NET included a PathInfo value in the value returned from various file path- related properties, including HttpRequest.FilePath, HttpRequest.AppRelativeCurrentExecutionFilePath, and HttpRequest.CurrentExecutionFilePath. ASP.NET 4 no longer includes the PathInfo value in the return values from these properties. Instead, the PathInfo information is available in HttpRequest.PathInfo.

13- ASP.NET 2.0 Applications Might Generate HttpException Errors that Reference eurl.axd
After ASP.NET 4 has been enabled on IIS 6, ASP.NET 2.0 applications that run on IIS 6 (in either Windows Server 2003 or Windows Server 2003 R2) might generate errors such as the following:
System.Web.HttpException: Path ‘/[yourApplicationRoot]/eurl.axd/[Value]‘ was not found.

14- Event Handlers Might Not Be Not Raised in a Default Document in IIS 7 or IIS 7.5 Integrated Mode
ASP.NET 4 includes modifications that change how the action attribute of the HTML form element is rendered when an extensionless URL resolves to a default document. An example of an extensionless URL resolving to a default document would be http://contoso.com/, resulting in a request to http://contoso.com/Default.aspx.

ASP.NET 4 now renders the HTML form element’s action attribute value as an empty string when a request is made to an extensionless URL that has a default document mapped to it. For example, in earlier releases of ASP.NET, a request to http://contoso.com would result in a request to Default.aspx. In that document, the opening form tag would be rendered as in the following example:


In ASP.NET 4, a request to http://contoso.com also results in a request to Default.aspx.
However, ASP.NET now renders the HTML opening form tag as in the following example:

15- Changes to the ASP.NET Code Access Security (CAS) Implementation
ASP.NET 2.0, and by extension the ASP.NET features that were added in 3.5, use the .NET Framework 1.1 and 2.0 code access security (CAS) model. However, the implementation of CAS in ASP.NET 4 has been substantially overhauled. As a result, partial-trust ASP.NET applications that rely on trusted code running in the global assembly cache (GAC) might fail with various security exceptions. Partial-trust applications that rely on extensive modifications to machine CAS policy might also fail with security exceptions.

16- MembershipUser and Other Types in the System.Web.Security Namespace Have Been Moved
Some types that are used in ASP.NET membership have been moved from System.Web.dll to the new System.Web.ApplicationServices.dll assembly. The types were moved in order to resolve architectural layering dependencies between types in the client and in extended .NET Framework SKUs.

17- Output Caching Changes to Vary * HTTP Header
In ASP.NET 1.0, a bug caused cached pages that specified Location=”ServerAndClient” as an output–cache setting to emit a Vary:* HTTP header in the response. This had the effect of telling client browsers to never cache the page locally.
In ASP.NET 1.1, the System.Web.HttpCachePolicy.SetOmitVaryStar method was added, which you could call to suppress the Vary:* header.

In ASP.NET 4, the decision was made to fix the root problem. The Vary:* HTTP header is no longer emitted from responses that specify the following directive:
<%@ OutputCache Location=”ServerAndClient” %>

18- System.Web.Security Types for Passport are Obsolete
The Passport support built into ASP.NET 2.0 has been obsolete and unsupported for a few years due to changes in Passport (now LiveID). As a result, the five types related to Passport in System.Web.Security are now marked with the ObsoleteAttribute attribute.

19- The MenuItem.PopOutImageUrl Property Fails to Render an Image in ASP.NET 4
In ASP.NET 3.5, the MenuItem.PopOutImageUrl property lets you specify the URL for an image that is displayed in a menu item to indicate that the menu item has a dynamic submenu. As a result of a design change in ASP.NET 4, no output is rendered for the PopOutImageUrl if the property is set for the MenuItem class.

20- Menu.StaticPopOutImageUrl and Menu.DynamicPopOutImageUrl Fail to Render Images When Paths Contain Backslashes
In ASP.NET 4, the images that you specify using the Menu.StaticPopOutImageUrl and Menu.DynamicPopOutImageUrl properties will not render if the path contains backlashes (\). This is a change from earlier versions of ASP.NET.

Monday, February 27, 2012

Difference between .Net 4.0 and .Net 3.5, 2.0


Difference between .Net 4.0 and .Net 3.5, 2.0

.Net Framework 4.0 comes up with some of major changes as compare to previous versions of .Net Framework 3.5 and 2.0

Following are list of Major Changes in .Net 4.0

C ControlRenderingCompatabilityVersion Setting in the Web.config File

ClientIDMode Changes

HtmlEncode and UrlEncode Now Encode Single Quotation Marks

ASP.NET Page (.aspx) Parser is Stricter

Browser Definition Files Updated

System.Web.Mobile.dll Removed from Root Web Configuration File

ASP.NET Request Validation

Default Hashing Algorithm Is Now HMACSHA256

Configuration Errors Related to New ASP.NET 4 Root Configuration

ASP.NET 4 Child Applications Fail to Start When Under ASP.NET 2.0 or ASP.NET 3.5 Applications

ASP.NET 4 Web Sites Fail to Start on Computers Where SharePoint Is Installed

The HttpRequest.FilePath Property No Longer Includes PathInfo Values

ASP.NET 2.0 Applications Might Generate HttpException Errors that Reference eurl.axd

Event Handlers Might Not Be Not Raised in a Default Document in IIS 7 or IIS 7.5 Integrated Mode Changes to the ASP.NET Code Access Security (CAS) Implementation

MembershipUser and Other Types in the System.Web.Security Namespace Have Been Moved

Output Caching Changes to Vary * HTTP Header

System.Web.Security Types for Passport are Obsolete

The MenuItem.PopOutImageUrl Property Fails to Render an Image in ASP.NET 4

Menu.StaticPopOutImageUrl and Menu.DynamicPopOutImageUrl Fail to Render Images When Paths Contain Backslashes


N.NET framework 2.0:

It brings a lot of evolution in class of the framework and refactor control including the support of

Generics
Anonymous methods
Partial class
Nullable type
The new API gives a fine grain control on the behavior of the runtime with regards to multithreading, memory allocation, assembly loading and more
Full 64-bit support for both the x64 and the IA64 hardware platforms
New personalization features for ASP.NET, such as support for themes, skins and webparts.
.NET Micro Framework


.NET framework 3.0:

Also called WinFX,includes a new set of managed code APIs that are an integral part of Windows Vista and Windows Server 2008 operating systems and provides

Windows Communication Foundation (WCF), formerly called Indigo; a service-oriented messaging system which allows programs to interoperate locally or remotely similar to web services.
Windows Presentation Foundation (WPF), formerly called Avalon; a new user interface subsystem and API based on XML and vector graphics, which uses 3D computer graphics hardware and Direct3D technologies.
Windows Workflow Foundation (WF) allows for building of task automation and integrated transactions using workflows.
Windows CardSpace, formerly called InfoCard; a software component which securely stores a person's digital identities and provides a unified interface for choosing the identity for a particular transaction, such as logging in to a website


.NET framework 3.5:

It implement Linq evolution in language. So we have the folowing evolution in class:

Linq for SQL, XML, Dataset, Object
Addin system
p2p base class
Active directory
ASP.NET Ajax
Anonymous types with static type inference
Paging support for ADO.NET
ADO.NET synchronization API to synchronize local caches and server side datastores
Asynchronous network I/O API
Support for HTTP pipelining and syndication feeds.
New System.CodeDom namespace.





Saturday, January 22, 2011

Exception Handling in C#


Exception Handling in C#


Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution.

C# provides three keywords try, catch and finally to do exception handling. The try encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any clean up process.

The general form try-catch-finally in C# is shown below

try
{
// Statement which can cause an exception.
}
catch(Type x)
{
// Statements for handling the exception
}
finally
{
//Any cleanup code
}

If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block.

But in C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks.


If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto.


In C#, exceptions are nothing but objects of the type Exception. The Exception is the ultimate base class for any exceptions in C#. The C# itself provides couple of standard exceptions. Or even the user can create their own exception classes, provided that this should inherit from either Exception class or one of the standard derived classes of Exception class like DivideByZeroExcpetion ot ArgumentException etc.


Uncaught Exceptions

The following program will compile but will show an error during execution. The division by zero is a runtime anomaly and program terminates with an error message. Any uncaught exceptions in the current context propagate to a higher context and looks for an appropriate catch block to handle it. If it can't find any suitable catch blocks, the default mechanism of the .NET runtime will terminate the execution of the entire program.


//C#: Exception Handling
//Author: rajeshvs@msn.com
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 100/x;
Console.WriteLine(div);
}
}

The modified form of the above program with exception handling mechanism is as follows. Here we are using the object of the standard exception class DivideByZeroException to handle the exception caused by division by zero.


//C#: Exception Handling
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("This line
in not executed");
}
catch(DivideByZeroException de)
{
Console.WriteLine("Exception occured");
}
Console.WriteLine("Result is {0}",div);
}
}

In the above case the program do not terminate unexpectedly. Instead the program control passes from the point where exception occurred inside the try block to the catch blocks. If it finds any suitable catch block, executes the statements inside that catch and continues with the normal execution of the program statements.

If a finally block is present, the code inside the finally block will get also be executed.


//C#: Exception Handling
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(DivideByZeroException de)
{
Console.WriteLine("Exception occured");
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine("Result is {0}",div);
}
}

Remember that in C#, the catch block is optional. The following program is perfectly legal in C#.


//C#: Exception Handling
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine("Result is {0}",div);
}
}

But in this case, since there is no exception handling catch block, the execution will get terminated. But before the termination of the program statements inside the finally block will get executed. In C#, a try block must be followed by either a catch or finally block.

Multiple Catch Blocks

A try block can throw multiple exceptions, which can handle by using multiple catch blocks. Remember that more specialized catch block should come before a generalized one. Otherwise the compiler will show a compilation error.


//C#: Exception Handling: Multiple catch
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(DivideByZeroException de)
{
Console.WriteLine("DivideByZeroException" );
}
catch(Exception ee)
{
Console.WriteLine("Exception" );
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine("Result is {0}",div);
}
}

Catching all Exceptions

By providing a catch block without a brackets or arguments, we can catch all exceptions occurred inside a try block. Even we can use a catch block with an Exception type parameter to catch all exceptions happened inside the try block since in C#, all exceptions are directly or indirectly inherited from the Exception class.


//C#: Exception Handling: Handling all exceptions
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch
{
Console.WriteLine("oException" );
}
Console.WriteLine("Result is {0}",div);
}
}

The following program handles all exception with Exception object.

//C#: Exception Handling: Handling all exceptions
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(Exception e)
{
Console.WriteLine("oException" );
}
Console.WriteLine("Result is {0}",div);
}
}

Throwing an Exception

In C#, it is possible to throw an exception programmatically. The 'throw' keyword is used for this purpose. The general form of throwing an exception is as follows.

throw exception_obj;

For example the following statement throw an ArgumentException explicitly.

throw new ArgumentException("Exception");

//C#: Exception Handling:
using System;
class MyClient
{
public static void Main()
{
try
{
throw new DivideByZeroException("Invalid Division");
}
catch(DivideByZeroException e)
{
Console.WriteLine("Exception" );
}
Console.WriteLine("LAST STATEMENT");
}
}

Re-throwing an Exception

The exceptions, which we caught inside a catch block, can re-throw to a higher context by using the keyword throw inside the catch block. The following program shows how to do this.

//C#: Exception Handling: Handling all exceptions
using System;
class MyClass
{
public void Method()
{
try
{
int x = 0;
int sum = 100/x;
}
catch(DivideByZeroException e)
{
throw;
}
}
}
class MyClient
{
public static void Main()
{
MyClass mc =
new MyClass();
try
{
mc.Method();
}
catch(Exception e)
{
Console.WriteLine("Exception caught here" );
}
Console.WriteLine("LAST STATEMENT");
}
}

Standard Exceptions

There are two types of exceptions: exceptions generated by an executing program and exceptions generated by the common language runtime. System.Exception is the base class for all exceptions in C#. Several exception classes inherit from this class including ApplicationException and SystemException. These two classes form the basis for most other runtime exceptions. Other exceptions that derive directly from System.Exception include IOException, WebException etc.

The common language runtime throws SystemException. The ApplicationException is thrown by a user program rather than the runtime. The SystemException includes the ExecutionEngineException, StaclOverFlowException etc. It is not recommended that we catch SystemExceptions nor is it good programming practice to throw SystemExceptions in our applications.

  • System.OutOfMemoryException
  • System.NullReferenceException
  • Syste.InvalidCastException
  • Syste.ArrayTypeMismatchException
  • System.IndexOutOfRangeException
  • System.ArithmeticException
  • System.DevideByZeroException
  • System.OverFlowException

User-defined Exceptions

In C#, it is possible to create our own exception class. But Exception must be the ultimate base class for all exceptions in C#. So the user-defined exception classes must inherit from either Exception class or one of its standard derived classes.

//C#: Exception Handling: User defined exceptions
using System;
class MyException : Exception
{
public MyException(string str)
{
Console.WriteLine("User defined exception");
}
}
class MyClient
{
public static void Main()
{
try
{
throw new MyException("RAJESH");
}
catch(Exception e)
{
Console.WriteLine("Exception caught here" + e.ToString());
}
Console.WriteLine("LAST STATEMENT");
}
}

Interfaces in C#


Interfaces in C# :


Introduction

Interfaces in C # provide a way to achieve runtime polymorphism. Using interfaces we can invoke functions from different classes through the same Interface reference, whereas using virtual functions we can invoke functions from different classes in the same inheritance hierarchy through the same reference. Before things start getting difficult let me start using simple and short examples to explain the concept of interfaces. Here's a short example that shows you what an interface looks like.

P1.cs

Collapse

class Demo
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
  }
}
 
interface abc
{  
}

Output

Collapse

Hello Interfaces

The above program compiles and runs successfully to produce the desired output. The above program consists of a class Demo and within it an entry point function Main() that prints Hello Interfaces. The above program also defines an interface abc. Interface abc is empty at this point of time. Let's add some elements to this interface.

P2.cs

Collapse

class Demo
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
  }
}
 
interface abc
{
  int x;  
}

Output

Collapse

P2.cs(11,3): error CS0525: Interfaces cannot contain fields

Error! Interfaces in C# cannot contain fields i.e variables. The above program declared an integer variable x in the interface abc. And that's what hit the C# compiler badly.

P3.cs

Collapse

class Demo
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
  }
}
 
interface abc
{
  void xyz()
  {
     System.Console.WriteLine("In xyz");
  }  
}

Output

Collapse

P3.cs(11,8): error CS0531: 'abc.xyz()': interface members cannot have a 
    definition

This time over we included a function xyz() inside the interface found that this too hurt the C# compiler. It told us loudly that interface members cannot have a defination. Does this mean that if we just have a function declaration inside the interface abc that is fine with the C# compiler? Let's find it out.

P4.cs

Collapse

class Demo
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
  }
}
 
interface abc
{
  void xyz();
}

Output

Collapse

Hello Interfaces

The above program compiles and runs successfully to produce the desired output. Finally we made the compiler happy. Interfaces in C# can only contain function declarations. Now let us see interfaces in action.

Interfaces are contracts that a class implements in its own way. This means an interface will contain function prototypes and a class that marries this interface will have to take the responsibility of defining the functions whose prototypes are declared by the marrying interface.

So its time to perform the marriage between our groom class Demo and the bride interface abc.

P4.cs

Collapse

class Demo : abc
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
  }
}
 
interface abc
{
  void xyz();
}

Output

Collapse

P4.cs(1,7): error CS0535: 'Demo' does not implement interface member 
    'abc.xyz()'
P4.cs(11,8): (Location of symbol related to previous error)

Well, in the above program class Demo did marry the interface abc through the line class demo : abc but as usual there's a small misunderstanding between the newlyweds. Class Demo needs to take the responsibility of defining the functions whose prototypes are declared by the marrying interface abc. Since class Demo in the above program has not been implemented i.e. defined the function xyz whose prototype is declared by the marrying interface abc we get an error in the above program. To fix this issue, the class Demo has to take the responsiility of defining the function xyz whose prototype is declared by the marrying interface abc. And that is what you get to see in the following program.

P5.cs

Collapse

class Demo : abc
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
  }
 
  void xyz()
  {
     System.Console.WriteLine("In xyz");
  }  
}
 
interface abc
{
  void xyz();
}

Output

Collapse

a.cs(1,7): error CS0536: 'Demo' does not implement interface member 
    'abc.xyz()'.'Demo.xyz()' is either static, not public, 
    or has  the wrong return type.
a.cs(16,8): (Location of symbol related to previous error)
a.cs(7,8): (Location of symbol related to previous error)

Error again! It's not enough for the class Demo to implement the function xyz. It has to impress the bride interface abc by declaring its implementation of xyz as public. And that's what is done by the following program.

P6.cs

Collapse

class Demo : abc
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
    xyz();
  }
 
  public void xyz()
  {
     System.Console.WriteLine("In xyz");
  }  
}
 
interface abc
{
  void xyz();
}

Output

Collapse

Hello Interfaces
In xyz

Bingo! The above program compiles and runs successfully to produce the desired output. As mentioned earlier using interfaces we can invoke functions from different classes using the same interface reference. For this, we need to have different classes to implement the same interface. In the above program our class Demo is implementing the interface abc. Let's have another class Sample that implements the interface abc.

P7.cs

Collapse

class Demo : abc
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
    Demo refDemo = new Demo();
    refDemo.xyz();
    Sample refSample = new Sample();
    refSample.xyz();    
  }
 
  public void xyz()
  {
     System.Console.WriteLine("In Demo :: xyz");
  }  
}
 
interface abc
{
  void xyz();
}
 
class Sample : abc
{
  public void xyz()
  {
     System.Console.WriteLine("In Sample :: xyz");
  }  
}

Output

Collapse

In Demo :: xyz
In Sample :: xyz

The above program compiles and runs successfully to produce the desired output. refDemo is a reference to the object of class Demo. refSample is a reference to the object of class Sample. Both the classes implement the interface abc and hence define their own implementation of the function xyz(). From within the entry point function Main() xyz() of the respective classes Demo and Sample are invoked through references refDemoand refSample.

Now that we have two different classes implementing the same interface its time to show you how to invoke functions from different classes using the same interface reference.

P8.cs

Collapse

class Demo : abc
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
    abc refabc = new Demo();
    refabc.xyz();
    abc refabc = new Sample();
    refabc.xyz();    
  }
 
  public void xyz()
  {
     System.Console.WriteLine("In Demo :: xyz");
  }  
}
 
interface abc
{
  void xyz();
}
 
class Sample : abc
{
  public void xyz()
  {
     System.Console.WriteLine("In Sample :: xyz");
  }  
}

Output

Collapse

In Demo :: xyz
In Sample :: xyz

The above program compiles and runs successfully to produce the desired output. Inside Main() we have an interface reference refabc of type interface abc. Reference of object of class Demo is stored in refabc andxyz() of class Demo is invoked using refabc. Next, the reference of object of class Sample is stored inrefabc and xyz() of class Sample is invoked using refabc. Thus, we were able to invoke xyz() that belongs to different classes Demo and Sample via a common interface reference refabc.

The following program uses a for loop to invoke the functions of different classes Demo and Sample that implement the same interface "interface abc" using a single interface reference refabc whose type matches the interface "interface abc" which the classes impliment.

P9.cs

Collapse

class Demo : abc
{
  public static void Main()
  {
    abc [] refabc = {new Demo(), new Sample()} ;
    for (int i = 0; i<= 1; i++)
      refabc[i].xyz();
  }
 
  public void xyz()
  {
     System.Console.WriteLine("In Demo :: xyz");
  }  
}
 
interface abc
{
  void xyz();
}
 
class Sample : abc
{
  public void xyz()
  {
     System.Console.WriteLine("In Sample :: xyz");
  }  
}

Output

Collapse

In Demo :: xyz
In Sample :: xyz

The above program compiles and runs successfully to produce the desired output. refabc is an array of type interface abc. It stores the references to objects of classes Demo and Sample. In the for loop, using the array refabc, we are invoking the function xyz() of class Demo and Sample. A class can impliment as many interfaces as it wants. Take the following program.

P10.cs

Collapse

class Demo : abc, def
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
    abc refabc = new Demo();
    refabc.xyz();
  }
 
  public void xyz()
  {
     System.Console.WriteLine("In xyz");
  }  
 
  public void pqr()
  {
     System.Console.WriteLine("In xyz");
  }
}
 
interface abc
{
  void xyz();
}
 
interface def
{
  void pqr();
}

Output

Collapse

Hello Interfaces
In xyz

The above program compiles and runs successfully to produce a desired output. Class Demo implements interfaceabc and thereby function xyz(). Class Demo also impliments interface def and thereby function pqr(). refabc which is a variable of type Interface abc, refers to object of class Demo. Next xyz() of Demo is invoked via refabc as refabc is a variable of type Interface abc which contains the prototype for function xyz().

P11.cs

Collapse

class Demo : abc, def
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
    abc refabc = new Demo();
    refabc.xyz();
    refabc.pqr();
  }
 
  public void xyz()
  {
     System.Console.WriteLine("In xyz");
  }  
 
  public void pqr()
  {
     System.Console.WriteLine("In xyz");
  }
}
 
interface abc
{
  void xyz();
}
 
interface def
{
  void pqr();
}

Output

Collapse

P11.cs(9,5): error CS0117: 'abc' does not contain a definition for 'pqr'

Error! An attempt to invoke pqr() of Demo via refabc fails as refabc is a variable of type Interface abcwhich contains the prototype for function xyz() and NOT pqr(). One can invoke pqr() of Demo via a reference variable of type Interface def as the interface def contains the prototype for function pqr(). And that's what is done by the following program.

P12.cs

Collapse

class Demo : abc, def
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
    Demo refDemo = new Demo();
    abc refabc = refDemo;
    refabc.xyz();
    def refdef = refDemo;
    refdef.pqr();
  }
 
  public void xyz()
  {
     System.Console.WriteLine("In xyz");
  }  
 
  public void pqr()
  {
     System.Console.WriteLine("In pqr");
  }
}
 
interface abc
{
  void xyz();
}
 
interface def
{
  void pqr();
}

Output

Collapse

Hello Interfaces
In xyz 
In pqr

The above program compiles and runs successfully to produce a desired output. Class Demo impliments the interfaces abc and def. An object of class Demo is created and its reference is stored in refDemo. refabcwhich is a variable of type Interface abc, refers to the object of class Demo. Next xyz() of Demo is invoked viarefabc as refabc is a variable of type Interface abc which contains the prototype for function xyz(). Similarly, refdef which is a variable of type Interface def, refers to object of class Demo. Next pqr() of Demois invoked via refdef as refdef is a variable of type Interface def which contains the prototype for functionpqr().

P13.cs

Collapse

class Demo : abc, def
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
    Demo refDemo = new Demo();
    abc refabc = refDemo;
    refabc.xyz();
    def refdef = refDemo;
    refdef.xyz();
  }
 
  public void xyz()
  {
     System.Console.WriteLine("In xyz");
  }  
}
 
interface abc
{
  void xyz();
}
 
interface def
{
  void xyz();
}

Output

Collapse

Hello Interfaces
In xyz
In xyz

The above program compiles and runs successfully to produce a desired output. Both the interfaces abc anddef declare the prototypes for function xyz(). Class Demo implements interfaces abc as well as def and defines the function xyz() as well. Thus we can invoke the function xyz() through either of the interface reference variables (refabc or refdef) after storing the reference to the object of class Demo in refabc orrefdef. This poses a question, how can we have an implementation of xyz that is specific to interface abcand implementation of xyz that is specific to def inside class Demo? Well, for this we need to use the fully qualified names as in the following program.

P14.cs

Collapse

class Demo : abc, def
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
    Demo refDemo = new Demo();
    abc refabc = refDemo;
    refabc.xyz();
    def refdef = refDemo;
    refdef.xyz();
  }
 
  public void abc.xyz()
  {
     System.Console.WriteLine("In abc.xyz");
  }  
 
  public void def.xyz()
  {
     System.Console.WriteLine("In def.xyz");
  }  
 
}
 
interface abc
{
  void xyz();
}
 
interface def
{
  void xyz();
}

Output

Collapse

a.cs(13,15): error CS0106: The modifier 'public' is not valid for this item
a.cs(18,15): error CS0106: The modifier 'public' is not valid for this item

Bummer! We used the fully qualified name and we got an error. That's because when we use fully qualified names for functions whose prototypes are a part of interfaces, the compiler doesn't need decorators like public. So we decided to remove the access specifier public from the above program.

P15.cs

Collapse

class Demo : abc, def
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
    Demo refDemo = new Demo();
    abc refabc = refDemo;
    refabc.xyz();
    def refdef = refDemo;
    refdef.xyz();
  }
 
  void abc.xyz()
  {
     System.Console.WriteLine("In abc.xyz");
  }  
 
  void def.xyz()
  {
     System.Console.WriteLine("In def.xyz");
  }  
 
}
 
interface abc
{
  void xyz();
}
 
interface def
{
  void xyz();
}

Output

Collapse

Hello Interfaces
In abc.xyz
In def.xyz

The above program compiles and runs successfully to produce a desired output. A fully qualified naming system allows us to define interfaces having same function prototypes. In the above example, interface abc and defcontain the same function prototypes for function xyz(). Class Demo impliments both the interfaces. Using fully qualified names, it defines implementation of xyz that is specific to interface abc and implementation of xyzthat is specific to interface def.

P16.cs

Collapse

class Demo : def
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
    Demo refDemo = new Demo();
    def refdef = refDemo;
    refdef.xyz();
    refdef.pqr();
  }
 
  public void xyz()
  {
     System.Console.WriteLine("In xyz");
  }  
 
  public void pqr()
  {
     System.Console.WriteLine("In pqr");
  }  
 
}
 
interface abc
{
  void xyz();
}
 
interface def : abc
{
  void pqr();
}

Output

Collapse

Hello Interfaces
In xyz
In pqr

The above program compiles and runs successfully to produce a desired output. Interfaces support inheritance. Interface def inherits prototypes from interface abc. Class Demo implements the interface def. Interface variable refdef stores the reference to object of class Demo. Functions xyz() and pqr() of class Demo are invoked through interface reference variable refdef.

What do you think of the fully qualified names of xyz() and pqr() would be after interface def inherits from interface abc.

P17.cs

Collapse

class Demo : def
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
    Demo refDemo = new Demo();
    def refdef = refDemo;
    refdef.xyz();
    refdef.pqr();
  }
 
  void def.xyz()
  {
     System.Console.WriteLine("In xyz");
  }  
 
  void def.pqr()
  {
     System.Console.WriteLine("In pqr");
  }  
 
}
 
interface abc
{
  void xyz();
}
 
interface def : abc
{
  void pqr();
}

Output

Collapse

P17.cs(12,8): error CS0539: 'def.xyz' in explicit interface declaration is 
    not a member of interface
P17.cs(29,11): (Location of symbol related to previous error)
P17.cs(1,7): error CS0535: 'Demo' does not implement interface member 
    'abc.xyz()'
P17.cs(26,8): (Location of symbol related to previous error)

Bummer! The prototype of function xyz is an original member of interface abc. Thus, even if interface definherits from the interface abc, the fully qualified name of the function xyz() remains as abc.xyz and notdef.xyz as done in the above program. In fact, we got a compiler error. This can be fixed by using the correct fully qualified name of function xyz() as shown in the following program.

P18.cs

Collapse

class Demo : def
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
    Demo refDemo = new Demo();
    def refdef = refDemo;
    refdef.xyz();
    refdef.pqr();
  }
 
  void abc.xyz()
  {
     System.Console.WriteLine("In xyz");
  }  
 
  void def.pqr()
  {
     System.Console.WriteLine("In pqr");
  }  
 
}
 
interface abc
{
  void xyz();
}
 
interface def : abc
{
  void pqr();
}

Output

Collapse

Hello Interfaces
In xyz
In pqr

The above program compiles and runs successfully to produce a desired output. But there are some pitfalls when using the fully qualified function names.

P19.cs

Collapse

class Demo : def
{
  public static void Main()
  {
    System.Console.WriteLine("Hello Interfaces");
    Demo refDemo = new Demo();
    refDemo.xyz();
    refDemo.pqr();
  }
 
  void abc.xyz()
  {
     System.Console.WriteLine("In xyz");
  }  
 
  void def.pqr()
  {
     System.Console.WriteLine("In pqr");
  }  
 
}
 
interface abc
{
  void xyz();
}
 
interface def : abc
{
  void pqr();
}

Output

Collapse

P19.cs(7,5): error CS0117: 'Demo' does not contain a definition for 'xyz'
P19.cs(8,5): error CS0117: 'Demo' does not contain a definition for 'pqr'

The above program fails to clear the compilation hurdle. refDemo refers to an object of class Demo. We are invoking xyz() using refDemo(). For C#, xyz() and ddd.xyz() are two different things. It knows thatabc.xyz() exists. It also knows that just xyz() is nowhere in the class. That's why we get an error which says Class Demo does not contain a definition of xyz(). For C#, abc.xyz() can be invoked by an interface reference of type abc only. Similarly, def.pqr() can be invoked by an interface reference of type def only.