Sunday, November 29, 2015

What is Singleton design pattern?


Singleton design pattern creates a class where single instance of class can be created throughout the application. Where ever object of that class is required same instance is used.
public sealed class Singleton
{
private static Singleton _instance = null;
private Singleton()
{
}
public static Singleton GetInstance()
{
lock (_instance)
{
if (_instance == null)
_instance = new Singleton();
}
return _instance;
}

}
Note: 
1. Singleton class should be sealed class so that it should not be derived further.
2. Singleton class constructor should be private to avoid class instance creation.
3. Multiple threading is handle through locking.
4. Singleton design pattern uses static property or method to create single instance.

Wednesday, November 25, 2015

Security in WCF

WCF is distributed programming platform . Using WCF, you can create applications that function as both services and service clients. Security in WCF provides Authentication, Authorization, Integrity, Confidentiality.
Why Security needed in WCF?
In distributed application or in the network there are malicious users, hackers always try to obtain sensitive information, phishing, alteration of messages etc. This gives way to a variety of message security threats.
Some example of security threats are mention below.
  • Phishing Attack
In this malicious user acts as online service and obtains user name, password etc. Then this malicious user transfers funds into his account. This is known as Phishing attack, which is very common now a days. Daily you must have received emails asking for username, password or you have won a lottery and asks for your Account number to credit the amount in your account .If you provide the information the malicious user transfers funds into his account .This is known as Phishing .
  • Stealing sensitive information from Network Traffic
The spy of other country intercept Network Traffic to obtain sensitive defence related information and use it to their advantage or in online–banking, client transfers funds from one account to another. A malicious user intercepts the message and having account number and password transfers funds into his account.
  • Alteration of messages to transfer funds in malicious user Account
Intercept messages sent through network and altering the account number to which deposit is made to transfer fund in malicious user Account.
  • Malicious user or Hacker replays the purchase order
Eg. Online shopping website receives hundreds of orders and sends items to Customers who have not even ordered them.
  • Authentication
The Service cannot assure that authorized person indeed performed the Transaction.
So after all this security is needed.
Windows Communication Foundation provides the basic security features that most distributed systems need. The big three protections— confidentiality, integrity, and authentication (or CIA as I like to think of them) are provided by most standard Windows® Communication Foundation bindings. If you don't want these protections, you'll have to turn them off, because they are on by default.
When you hear people say, "Windows Communication Foundation is secure by default," understand that they are probably talking about CIA.

2. Security Choices in Windows Communication Foundation

First step to secure WCF is to define security policy. When you expose a service endpoint you also select a binding for proper communication protocol and message encoding format.
Example-For intranet communications or systems behind the firewall, TCP protocol with binary message encoding is preferred. For Internet access, HTTP protocol is a typical choice using text or MTOM encoding (depending on the message size).
You don’t need to make just one choice. You can expose contract over many bindings.
A standard set of bindings satisfy these protocol and encoding choices.
· NetTcpBinding is the right choice for binary TCP communications that cross machine boundaries.
· BasicHttpBinding is the right choice for HTTP communications that must support legacy Web service protocols.
· WSHttpBinding orWSFederationHttpBinding are the right choice for Web services that can leverage a richer set of standards including those for secure communications.
Beyond bindings, behaviours also provide information about client and service credentials, and affect how authorization is handled.
You can configure bindings and behaviours declaratively or through the runtime object model.
Each binding provides default security settings. The two important knobs in security settings are security mode( transport versus message security) and Client Credential.
Transport Security
In Transport security transports available for use are HTTP, TCP, IP and MSMQ. All communication that takes place across the channel must be encrypted.
Advantage of using Transport security:
Less chances of Message Alteration, Sniffing network, Phishing and replay of message attack.
Transport level security provides
Authentication of the sender service, Message integrity, Confidentiality and Replay of message detection.
When you configure security for WCF binding, you'll need to decide whether you want CIA to be provided at the transport level or at the message level.
If you configure wsHttpBinding for transport security, WCF will not supply CIA for your messages. You need to run URI over HTTPS . If you're hosting inside IIS, you'll need to install an SSL certificate for the Web site. On the other hand, if you're hosting in your own process and using HTTP.SYS directly, you'll need to register a certificate with HTTP.SYS, either programmatically or via the command-line tool, HTTPCFG.EXE.
For Intranet where both client and service use WCF, netTcpBinding with transport security might be a better choice. It performs better due to its binary encoding.
Message Security
Message Security is applied at the message layer which is transport independent. It has maximum flexibility in terms of having the message routed over different transports. WS-Security defines different ways to secure a message and the tokens that can be used. Message Security is slowest in terms of performance.
You can provide CIA at the transport level, you can choose to push these details down into the SOAP messages themselves by using message security.
Eg wsHttpBinding By default it uses message-level security, assuming the service and the client will identify and authenticate themselves using Windows credentials. Body and most headers are signed to maintain the integrity of the message and the body is encrypted. An attacker looking at a message trace would see the SOAP envelope in the clear, but the SOAP body would contain an EncryptedData element full of base64-encoded ciphertext.
Mixed Mode
WCF also allows you to mix transport and message security. At Transport level confidentiality, integrity and authentication are provided (therefore the entire bytestream is encrypted, not just the message body). Client authentication is performed at the message level. The client can then use WS-Security to send any shape of credential that she wants.
Credentials
After deciding whether to use either transport or message security (or mixed mode), and assuming you've not chosen a security mode of None, the next major decision is the shape of credential that the client and service will use.
Credential is used to provide verification of identity.
WCF GIVES client credential type. There are at least five options for client credentials, although some options may not be available in certain contexts

3. Default Security in Standard Bindings

The three most popular standard bindings are basicHttpBinding, wsHttpBinding, and netTcpBinding. The simplest is basicHttpBinding.This doesn't provide CIA by default. This type of binding is secured by running over HTTPS. For this you'll need to change the binding to let WCF know you'll be using transport security:
i). basicHttpBinding

Now  deploy this  in IIS and turn on SSL support for your virtual directory. Install a certificate for the Web site.  If you're deploying in IIS and plan to require client certificates, change the clientCredentialType to Certificate.
ii). wsHttpBinding
The next binding, wsHttpBinding, uses message security by default. The default client credential type is Windows. You can use this binding to switch it to use TransportWithMessageCredential. Here you'll use an HTTPS endpoint to provide authentication, integrity, and confidentiality, while the client credential remains in the SOAP Security header for flexibility. SOAP envelope with header is encrypted by the transport. There are some disadvantages, however, such as the lack of end-to-end security at the message level.

  




    




    




  


iii). netTcpBinding
If you want raw speed for Web services intranet use netTcpBinding .This binding uses transport security with Windows credentials. The default binding uses transport security.

  


binding="netTcpBinding" contract="IFoo" >
iv). Implement Transport security
SAMPLE WCF SERVICE
Step 1:
Click on new project and select WCF service project.

public class Service1 : IService1




{




public string GetData(int value)




{




return string.Format("The Value entered: {0}", value);




}




public CompositeType GetDataUsingDataContract(CompositeType composite)




{




if (composite.BoolValue)




{




composite.StringValue += "Add";




}




return composite;




}


}
Step 2:
To enable transport security in WsHttp binding. This is done using the ‘Security’ XML tag as shown in the below code snippet.







Step 3: Tie up the Binding and specify HTTPS Configuration
Now use the ‘bindingConfiguration’ tag to specify the binding name. We also need to specify the address where the service is hosted. HTTS in the address tag.
Change ‘mexHttpBinding’ to ‘mexHttpsBinding’ in the second end point





In the ‘serviceMetadata’ we also need to change ‘httpGetEnabled’ to ‘httpsGetEnabled’.

........




.........






.........




.........



Step 4: Make the Application HTTPS enabled
Compile the WCF service project and host the same in IIS application with HTTPS enabled.

Code for consuming Service-




using System;




using System.Collections.Generic;




using System.Linq;




using System.Web;




using System.Web.UI;




using System.Web.UI.WebControls;




using WebApplicationConsumer.ServiceReference1;




using System.Net;




using System.Net.Security;




using System.Security.Cryptography.X509Certificates;





namespace WebApplicationConsumer




{




public partial class _Default : System.Web.UI.Page




{





protected void Page_Load(object sender, EventArgs e)




{




ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler); 




Service1Client obj = new Service1Client();




Response.Write(obj.GetData(007));




}




public static bool IgnoreCertificateErrorHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)




{




return true;




}




}


}
Step 5: Now compile the Application.

v). Implement Message Level Security
Step 1: Create Client and Server Certificates using makecert.
Step 2:
In the web.config file of the WCF service.



storeLocation="CurrentUser"
storeName="MyArticle"
x509FindType="FindBySubjectName" />
Step 3. Define Bindings
I have defined the ‘WsHttpBinding’ with message attribute specifying that the WCF client needs to send a certificate for validation.




      





Step 4 :Tie the Bindings with the End point
Use ‘bindingConfiguration’ tag as shown in the below code snippet.

bindingConfiguration"BACKGROUND-COLOR: #ffff00">="wsHttpEndpointBinding" contract="WCFServiceCertificate.IService1">


Step 5 : Make Application to Consume the Web Service
Compile the WCF service and reference the same in the ASP.NET web application using ‘Service reference’. Below is the code snippet where we have referenced the service and called the ‘GetData’ function of the service.

using System;




using System.Collections.Generic;




using System.Linq;




using System.Web;




using System.Web.UI;




using System.Web.UI.WebControls;




"BACKGROUND-COLOR: #ffff00">using WebConsumer.ServiceReference1;




namespace WebConsumer




{




public partial class _Default : System.Web.UI.Page




{




protected void Page_Load(object sender, EventArgs e)




{




"BACKGROUND-COLOR: #ffff00">Service1Client obj = new Service1Client();




"BACKGROUND-COLOR: #ffff00">Response.Write(obj.GetData(12));




}




}




}


Step 6 : Define Certificates in WCF Client
I have set authentication mode as ‘peertrust’ and we have specified the client certificate name as ‘WcfClient’.











Step7 : Tie up the behavior with end point on WCF client
Now bound the behavior using ‘behaviorConfiguration’ property. We also need to specify that the DNS value .

bindingConfiguration="WSHttpBinding_IService1" contract="ServiceReference1.IService1"
name="WSHttpBinding_IService1"
"BACKGROUND-COLOR: #ffff00">behaviorConfiguration="CustomBehavior">
"BACKGROUND-COLOR: #ffff00">
Step 8 : Now run the Application.



Tuesday, November 24, 2015

Tips to Improve the Performance of an ASP.Net Application

 Here are a few tips to improve the performance of your ASP.Net application.
  1. Viewstate
    View state is the wonder mechanism that shows the details of the entry posted on the server. It is loaded every time ifrom the server. This option looks like an extra feature for the end users. This needs to be loaded from the server and it adds more size to the page but it will affect the performance when we have many controls in the page, like user registration. So, if there is no need for it then it can be disabled.

    EnableViewState = "false" needs to be given based on the requirements. It can be given at the control, page and config level settings.
     
  2. Avoid Session and Application Variables
    A Session is a storage mechanism that helps developers to take values across the pages. It will be stored based on the session state chosen. By default it will be stored in the Inproc. That default settings uses IIS. When this Session variable is used in a page that is accessed by many numbers then it will occupy more memory allocation and gives additional overhead to the IIS. It will make the performance slow.

    It can be avoided for most scenarios . If you want to send the information across pages then we can use a Cross Post-back, Query string with encryption. If you want to store the information within the page then caching the object is the best way.
     
  3. Use Caching
    ASP.Net has the very significant feature of a caching mechanism. It gives more performance and avoids the client/server process. There are three types of caching in ASP.Net.

    If there is any static content in the full pages then it should be used with the Output cache. What it does is, it stores the content on IIS. When the page is requested it will be loaded immediately from the IIS for the certain period of time. Similarly Fragment paging can be used to store the part of the web page.
     
  4. Effectively use CSS and Script files
    If you have large CSS files that are used for the entire site in multiple pages, then based on the requirements, it can be split and stored with different names. It will minimize the loading time of the pages.
     
  5. Images sizes
    Overuse of images in the web site affect the web page performance. It takes time to load the images, especially on dial-up connections. Instead of using the background images, it can be done on the CSS colors or use light-weight images to be repeated in all of the pages.
     
  6. CSS based layout
    The entire web page design is controlled by the CSS using the div tags instead of table layout. It increases the page loading performance dramatically. It will help to enforce the same standard guideline throughout the website. It will reduce the future changes easily. When we use the nested table layout it takes more time for rendering.
     
  7. Avoid Round trips
    We can avoid unnecessary database hits to load the unchanged content in the database. We should use the IsPostBack method to avoid round trips to the database.
     
  8. Validate using JavaScript

    Manual validation can be done at the client browser instead of doing at the server side. JavaScript helps us to do the validation at the client side. This will reduce the additional overhead to the server.

    The plug-in software helps to disable the coding in the client browser. So, the sensitive application should do the server side validation before going into the process. 
     
  9. Clear the Garbage Collection

    Normally .Net applications use Garbage Collection to clean the unused resources from memory. But it takes time to clear the unused objects from memory.

    There are many ways to clean the unused resources. But not all of the methods are recommended. But we can use the dispose method in the finally block to clean up the resources. Moreover we need to close the connection. It will immediately free the resources and provides space in memory.
     
  10. Avoid bulk data store on client side

    Try to avoid more data on the client side. It will affect the web page loading. When we store more data on the hidden control then it will be encrypted and stored on the client side. It can be tampered with by hackers as well.
     
  11. Implement Dynamic Paging
    When we load a large number of records into the server data controls like GridView, DataList and ListView it will take time to load. So we can show only the current page data through the dynamic paging.
     
  12. Use Stored Procedure

    Try to use Stored Procedures. They will increase the performance of the web pages. Because it is stored as a complied object in the database and it uses the query execution plans. If you pass the query then it will make a network query. In the Stored Procedure a single line will be passed to the backend.
     
  13. Use XML and XSLT

    XML and XSLT will speed up the page performance. If the process is not more complex then it can be implemented in XSLT.
     
  14. Use Dataset

    A DataSet is not lightweight compared with DataReader. But it has the advantages of a disconnected architecture. A DataSet will consume a substantial amount of memory. Even though it can have more than one day. If you want to perform many operations while loading the page itself, then it might be better to go with a DataSet. Once data is loaded into the DataSet it can be used later also.
     
  15. Use String Builder in place of String

    When we append the strings like mail formatting in the server side then we can use StringBuilder. If you use string for concatenation, what it does every time is it creates the new storage location for storing that string. It occupies more spaces in memory. But if we use the StringBuilder class in C# then it consumes more memory space than String.
     
  16. Use Server.Transfer

    If you want to transfer the page within the current server then we can use the Server.Transfer method. It avoids roundtrips between the browser and server. But it won't update the browser history.
     
  17. Use Threads

    Threads are an important mechanism in programming to utilize the system resources effectively. When we want to do a background process then it can be called a background process.

    Consider the example of when clicked on send, it should send the mail to 5 lakhs members yet there is no need to wait for all the processes to complete. Just call the mail sending process as a background thread then proceed to do the further processing, because the sending of the mail is not dependent on any of the other processes.

Sunday, November 22, 2015

Exception handling SQL Server Store procedure.

Exception handling was biggest problem in store procedure before SQL Server 2005. This features has been provided in SQL Server 2005. Exception handling is same as other languages like C#, C++ etc. TRY..CATCH block is used for exception handing.
TRY..CATCH Syntax
  1. BEGIN TRY
  2. --T-SQL statements / blocks
  3. END TRY
  4. BEGIN CATCH
  5. --T-SQL statements / blocks
  6. END CATCH
Example1: Error handling
  1. Create proc Testproc
  2. as
  3. begin
  4. BEGIN TRY
  5.  -- Generate divide-by-zero error.
  6.     SELECT 1/0;
  7. END TRY
  8. BEGIN CATCH
  9. PRINT 'DIVIDE BY ZERO'
  10. END CATCH
  11. End
Functions to be used in CATCH block are :
  • ERROR_NUMBER: returns the error number, and is the same value of @@ERROR.
  • ERROR_SEVERITY: returns the severity level of the error that invoked the CATCH block.
  • ERROR_STATE: returns the state number of the error.
  • ERROR_PROCEDURE: returns the name of the stored procedure or trigger for which the error occurred.
  • ERROR_LINE: returns the line number where the error occurred.
  • ERROR_MESSAGE: returns the full message text of the error. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times.
  • You can use these functions anywhere inside a CATCH block, and they will return information regarding the error that has occurred. These functions will return the value null outside of the CATCH block. 
  1. -- Create procedure to get error information.
  2. CREATE PROCEDURE GetErrorInfo
  3. AS
  4. begin
  5. SELECT
  6. ,ERROR_SEVERITY()
  7. AS ErrorSeverity
  8. ERROR_NUMBER()
  9. AS ErrorNumber
  10. ,ERROR_STATE()
  11. AS ErrorState
  12. ,ERROR_MESSAGE()
  13. AS ErrorMessage;
  14. ,ERROR_PROCEDURE()
  15. AS ErrorProcedure
  16. ,ERROR_LINE()
  17. AS ErrorLine
  18. GO
  19. End
Use this store procedure in another store procedure
 to handle error
  1. Create proc DividebyZero
  2. BEGIN TRY
  3. -- Generate divide-by-zero error.
  4. SELECT
  5. 1/0;
  6. END TRY
  7. -- Execute error retrieval routine.
  8. BEGIN
  9. CATCH
  10. EXECUTE GetErrorInfo;
  11. END CATCH
Points to remember:
        
1. A TRY…CATCH construct catches all execution errors that have a severity higher than 10 that do not close the database.
2. A TRY block must be immediately followed by an associated CATCH block.
3. . A TRY…CATCH construct cannot span multiple batches. A TRY…CATCH construct cannot span multiple blocks of Transact-SQL statements.           4. When the code in the CATCH block finishes, control passes to the statement immediately after the END CATCH statement.   5. TRY…CATCH constructs can be nested. Either a TRY block or a CATCH block can contain nested TRY…CATCH constructs.  6. Errors encountered in a CATCH block are treated like errors generated anywhere else. If the CATCH block contains a nested TRY…CATCH construct, any error in the nested TRY block will pass control to the nested CATCH block. If there is no nested TRY…CATCH construct, the error is passed back to the caller.  7. If the stored procedure does not contain its own TRY…CATCH construct, the error returns control to the CATCH block associated with the TRY block that contains the EXECUTE statement.  8. If the stored procedure contains a TRY…CATCH construct, the error transfers control to the CATCH block in the stored procedure. When the CATCH block code finishes, control is passed back to the statement immediately after the EXECUTE statement that called the stored procedure.          9. GOTO statements cannot be used to enter a TRY or CATCH block. GOTO statements can be used to jump to a label inside the same TRY or CATCH block or to leave a TRY or CATCH block.          10. The TRY…CATCH construct cannot be used in a user-defined function.          11. The CATCH block is executed only if there is an error occurs in T-SQL statements within TRY block otherwise the CATCH block is ignored.          12. Each TRY block is associated with only one CATCH block and vice versa          13. TRY and CATCH blocks can’t be separated with the GO statement. We need to put both TRY and CATCH blocks within the same batch.         14. TRY..CATCH blocks can be used with transactions. We check the number of open transactions by using @@TRANCOUNT function in Sql Server.       15 XACT_STATE function within the TRY..CATCH block can be used to check whether a open transaction is committed or not. It will return -1 if transaction is not committed else returns 1.
Limitation of TRY…CATCH:
·        Compiled errors are not caught.
· Deferred name resolution errors created by statement level recompilations. (If process is terminated by Kill commands or broken client connections TRY…CATCH will be not effective)
·  Errors with a severity greater than 10 that do not terminate their database connection are caught in the TRY/CATCH block.
·    For errors that are not trapped, SQL Server 2005 passes control back to the application immediately, without executing any CATCH block code.

Thursday, November 19, 2015

What is Extension methods in C#?

What is extension method?
Extension method enable us to add a method in types without modifying , recompiling or deriving existing types.
Extension method is static method but called as instance method of types. 
                      Extension method is declared as static in static class where 'this' modifier is first parameter.
The type of first parameter is type that is extended.   
                                            
Extension methods has following features:
1. Sealed class can be extended using extension method.
2. Extension method should not extended method with same signature from type.
3. Extension method cannot be used to override the existing method.
4. Concept of extension method cannot be applied to fields, properties and event.

Ex: I am going to extend the assembly which i have created.


Create class library with name ClassLibrary1 using Visual studio. Add following code to library.

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

namespace ClassLibrary1
{
    public class Class1
    {
        public string Disp()
        {
            return "yes";
        }
    }
}

Now create a console application ConsoleApplication2.
Now add following code to console application.

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

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            ClassLibrary1.Class1 c = new ClassLibrary2.Class1();
            c.Show();
            c.Disp();
            
            Console.ReadLine();
        }
    }


    public static class sub
    {

        public static void Show(this ClassLibrary2.Class1 cls)
        {

            Console.WriteLine("show");
        }
    }
}

Method Show is available in Class1 of ClassLibrary2.

How to extend the sealed class in c#?

Sealed class can be extended using the extension method.

Sunday, November 15, 2015

When abstract class need not be inherited?

Abstract class should be inherit always, If you don't want to inherit then mark sub class as abstract class using abstract keyword.

Saturday, November 14, 2015

HCL interview questions and answers for experience.



1. Differences between VS 2005, 2008 and 2010?

VS 2005 support the then new .net framework 2.0 visual studio 2008 came out to support 3.0 and 3.5 while visual studio 2010 supports the upcoming .net framework 4.0.

Also since the release of visual studio 2008 all newer versions are now backwards compatible to older frameworks. Meaning in visual studio 2008 you are able to work with .net framework 2.0 applications as well as the at the time new 3.0 and 3.5 frameworks. This means the new visual studio 2010 will support development of framework versions 2.0, 3.0, 3.5 and 4.0. Visual studio 2008 however will only support 2.0, 3.0 and 3.5.

2. Differences between static and instance constructor?

Static Constructor

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.
class MyClass
{
    // Static variable that must be initialized at run time.
    static readonly long ticks;

    // Static constructor is called at most one time, before any
    // instance constructor is invoked or member is accessed.
    static MyClass()
    {
        ticks= DateTime.Now.Ticks;
    }
}
Static constructors have the following properties:
  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
  • If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.
In this example, class Bus has a static constructor. When the first instance of Bus is created (bus1), the static constructor is invoked to initialize the class. The sample output verifies that the static constructor runs only one time, even though two instances of Bus are created, and that it runs before the instance constructor runs.
Instance Constructor
Instance constructor is used to initialize instance data. Instance constructor is called every time when object of class is created. It is called explicitly. Instance constructor takes parameters. It has access specifiers.

3. Difference between Abstract class and interface?


InterfaceAbstract class
Interface support multiple inheritanceAbstract class does not support multiple inheritance
Interface doesn't Contains Data MemberAbstract class contains Data Member
Interface doesn't contains ConstructorsAbstract class contains Constructors
An interface Contains only incomplete member (signature of member)An abstract class Contains both incomplete (abstract) and complete member
An interface cannot have access modifiers by default everything is assumed as publicAn abstract class can contain access modifiers for the subs, functions, properties
Member of interface can not be StaticOnly Complete Member of abstract class can be Static


When to use abstract class or Interface?
  • An interface is like a contract. It says that a class which implements the interface agrees to implement all of the functions declared (as signatures only; no function definition) by that interface. The class may do so in any way it chooses, and provide any other functionality, as long as it implements each one of the declared functions. An interface is useful when you want to be able to use some common functionality of otherwise unrelated classes- they share no implementation details, only the function signatures. In C#, function declarations within an interface are implicitly pure virtual.
    An abstract class is a partially defined class that cannot be instantiated. It (usually) includes some implementation, but leaves some functions as pure virtual- declared only by their signature. Pure virtual functions are not defined in the class that declares them, so they must be implemented by a subclass (unless it too is an abstract class). Only a subclass which defines all of the pure virtual functions can be instantiated. The purpose of an abstract class is to define some common behavior that can be inherited by multiple sub-classes, without implementing the entire class. In C#, the abstract keyword designates both an abstract class and a pure virtual method.
    In practical terms, the difference between the two is that an interface defines only pure virtual functions, while an abstract class may also include concrete functions, members, or any other aspect of a class.
Interfaces are like skeletons. If you want to build a human, you should use that skeleton.
Interfaces simply create a kind of structure for your classes to denote that your class should have a defined and agree-upon structure. For example, all animals pee, eat and make sounds. Thus you can have an interface, called IAnimal which only mentions that classes should PeeEat, and MakeSound.
Interfaces are just like simple checklists, which should either be implemented totally, or none. When you want to use IAnimal interface, it's just like your boss telling you "Hey, don't create a Cat class unless you write some methods for it to eat, pee, and make sound".
Abstract classes are like skeletons, but with some meat on them as well. It's just there to make your work easier.
You can consider an abstract class to be an interface, which already has some implementation.
That was the plain English answer. But after getting that, please study more, to get the real concept.

An abstract class is a class. It is special in that you cannot create object of abstract class. A non-abstract class in called concrete class.
An abstract class, being a class, can have usual elements in it like fields, properties, methods events, indexers etc. Note that, as it is guaranteed that abstract class will not be instantiated to create object, some of those elements cab be without implementations (e.g. methods without body).
An interface is description of members that some other class will have for sure. C# interface can describe methods, properties, indexers and events only.
If a class implements interface, then it must implement all members described by interface.
This means if a class, implementing an interface, does not implement all members described by that interface then such class must be abstract class!
An abstract class can be 'half-cooked' class meaning it has provided few methods with body but few methods are without body etc. An interface can never implement any member it describes.
Abstract class takes part in hierarchy of classes based on inheritance. Note that in C#, a class can have at most one parent class which may or may not be abstract.
A class can implement many interfaces at the same time.
There many use cases for both of them.
Following statements should give you more clarity:
  • Class must be either abstract or concrete.
  • Interface, by definition, is abstract.
  • Neither interface nor abstract class can be instantiated.
  • Class may inherit from zero or one (abstract or concrete) class.
  • Class may implement zero or more interfaces.
  • Interface may inherit from zero or more interfaces.
  • Interface cannot inherit a class.
  • Abstract class may have members with implementation.
  • Interface cannot have any member with implementation.
  • To be concrete, class must implement all members in interface.
Use Abstract class when there is a 'IS-A' relationship between classes. For example, Lion is a Animal, Cat is an Animal. So, Animal can be an abstract class with common implementation like no. of legs, tail etc.


Abstract classes allow you to provide default functionality for the subclasses. If you plan on updating this base class throughout the life of your program, it is best to allow that base class to be an abstract class. Why? Because you can make a change to it and all of the inheriting classes will now have this new functionality. If the base class will be changing often and an interface was used instead of an abstract class, we are going to run into problems. Once an interface is changed, any class that implements that will be broken. Now if its just you working on the project, that’s no big deal. However, once your interface is published to the client, that interface needs to be locked down. At that point, you will be breaking the clients code.


Speaking from personal experiences, frameworks is a good place to show when and where to use both an abstract class and an interface. Another general rule is if you are creating something that provides common functionality to unrelated classes, use an interface. If you are creating something for objects that are closely related in a hierarchy, use an abstract class. An example of this would be something like a business rules engine. This engine would take in multiple BusinessRules as classes perhaps? Each one of these classes will have an analyze function on it.
Basically Abstract class should be used for 'is-a' relationship and Interface should be used for 'has-a' relationship.
If we want to retrict all the subclasses must have certain functionality, then Abstract class with implementation is recomended. So, overriding already implemented member in the subclasses is not a good practice here.

In a particular class, where there are more behaviours that will get change during runtime, then implementing from multiple interfaces are recommended. 
Use an abstract class
When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. (COM was designed around interfaces.)
Use an abstract class to define a common base class for a family of types.
Use an abstract class to provide default behavior.
Subclass only a base class in a hierarchy to which the class logically belongs.
Use an interface
When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility.
Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.
Use an interface to design a polymorphic hierarchy for value types.
Use an interface when an immutable contract is really intended.
A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.


Important rules applied to abstract classes

An abstract class cannot be a sealed class. I.e. the following declaration is incorrect.
//Incorrect
abstract sealed class absClass
{
}
Declaration of abstract methods are only allowed in abstract classes.
An abstract method cannot be private.
//Incorrect
private abstract int MultiplyTwoNumbers();
The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.
An abstract method cannot have the modifier virtual. Because an abstract method is implicitly virtual.
//Incorrect
public abstract virtual int MultiplyTwoNumbers();
An abstract member cannot be static.
public abstract static int MultiplyTwoNumbers();
4. What is collection?
Collection classes are specialized classes for data storage and retrieval. These classes provide support for stacks, queues, lists, and hash tables. Most collection classes implement the same interfaces.


Collection classes serve various purposes, such as allocating memory dynamically to elements and accessing a list of items on the basis of an index etc. These classes create collections of objects of the Object class, which is the base class for all data types in C#.
Ex: ArrayList, Stack Queue etc.

5. Diff between ArrayList and List?

 1. ArrayList is collection class. Stored data in form of object.
When you stored data or retrieve data boxing and unboxing takes place.
It is costly operation and it hinders performance.

  ArrayList arrayList = new ArrayList();
            arrayList.Add("1");
            arrayList.Add("One");

            Console.WriteLine(arrayList[0].ToString());//Output 1

2. List is generic collection and it stores generic data so no boxing and unboxing involves.
  List list = new List();
            list.Add(1);
            list.Add("1");//error
            list.Add(2);


            Console.WriteLine(list[0]);//1

6. Difference between overriding and hidding?


What are the differences between method hiding and overriding in C#?
  1. For hiding the base class method from derived class simply declare the derived class method with the new keyword.
    Whereas in C#, for overriding the base class method in a derived class, you need to declare the base class method as virtual and the derived class method as overriden.
  2. If a method is simply hidden then the implementation to call is based on the compile-time type of the argument "this".
    Whereas if a method is overridden then the implementation to be called is based on the run-time type of the argument "this".
  3. New is reference-type specific, overriding is object-type specific.
What are the differences between method hiding and method shadowing?
  1. Shadowing is a VB concept. In C#, this concept is called hiding.
  2. The two terms mean the same in C#.
    Method hiding == shadowing
  3. In short, name "hiding" in C# (new modifier) is called shadowing in VB.NET (keyword Shadows).
  4. In C# parlance, when you say "hiding" you're usually talking about inheritance, where a more derived method "hides" a base-class method from the normal inherited method call chain.
  5. When you say "shadow" you're usually talking about scope; an identifier in an inner scope is "shadowing" an identifier at a higher scope.
  6. In other languages, what is called "hiding" in C# is sometimes called "shadowing" as well.

7. These static constructors are correct?

class A
statc intA()
{
}
static A(int x,int y)
{
}
static A(int x)
}

Ans: A static constructor does not take access modifiers or have parameters.


8. This abstract class is correct?
abstract class A
{

public abstract void Disp();

public abstract void B()
{

}

public absract virtual C()
{

}



}

Ans:  Method without implementation is called abstract method. It is declared with abstract key word. Please see inline comment.



abstract class A
{

public abstract void Disp();//correct

public abstract void B() //wrong 
{

}

public absract virtual C() //wrong
{

}



}

Write a program to reverse a string? using System; namespace ConsoleApp1 {     class Program     {         static void Main(string[] args)  ...