Frequently Asked ASP.NET Questions

  • .NET is a developer platform made up of tools, programming languages, and libraries for building many different types of applications.
    ASP.NET extends the .NET developer platform with tools and libraries specifically for building web apps.

    Features Of ASP.Net
    1. Fast and scalable : ASP.NET performs faster than any popular web framework.
    2. Build secure apps : ASP.NET supports industry standard authentication protocols. Built-in features help protect your apps against cross-site scripting (XSS) and cross-site request forgery (CSRF).
    ASP.NET provides a built-in user database with support for multi-factor authentication and external authentication with Google, Twitter, and more.
    3. Active community and open-source : It as a wide range of active community of developers including Stackoverflow and Asp.net fourms.
    NET is open source on GitHub, with over 100,000 contributions and 3,700 companies already contributing.
    4. Free hosting on Azure : Get 10 ASP.NET websites for free with Microsoft Azure.
    You can also deploy to any major cloud platform, your own Linux or Windows servers, or one of many hosting providers.

  • ASP.NET is an open-source server-side application framework designed for web developers to produce dynamic web pages with .NET framework. It was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services. It provides many re-usable components to develop dynamic applications.

    ASP.Net applications can also be written in a variety of .Net languages. These include C#, VB.Net, and J#.

    The architecture of the.Net framework is based on the following key components

    1. Language – A variety of languages exists for .net framework. They are VB.net and C#. These can be used to develop web applications.
    2. Library - The .NET Framework includes a set of standard class libraries. The most common library used for web applications in .net is the Web library. The web library has all the necessary components used to develop.Net web-based applications.
    3. Common Language Runtime - The Common Language Infrastructure or CLI is a platform. .Net programs are executed on this platform. The CLR is used for performing key activities. Activities include Exception handling and Garbage collection.

  • A postback is a request sent from a client to a server from the same page that the user is already working with. ASP.NET was introduced with a mechanism to post an HTTP POST request back to the same page. It’s basically posting a complete page back to server (i.e. sending all of its data) on the same page. So, the whole page is refreshed.

    When user requests a page for the first time the IsPostback property value will be false, When user fills the form and press submit button Then the whole page will be transfred to server and this time IsPostback property vales will be true.

    Call back : A callback is generally a call for execution of a function after another function has completed.
    But if we try to differentiate it from a postback then we can say that it is a call made to the server to receive specific data instead of an entire page refresh like a postback. In ASP.NET, it's done using AJAX, that makes a call to the server and updates a part of the page with the specific data received.

  • ASP.NET Web Forms uses Page controller pattern approach for rendering layout. In this approach, every page has it's own controller, i.e., code-behind file that processes the request. On the other hand, ASP.NET MVC uses Front Controller approach. In this approach, a common controller for all pages, processes the requests.

    ASP.NET MVC is a web application framework for the .NET Platform used for building full stack web applications using the Model-View-Controller pattern.

    Difference between ASP.NET MVC and WebForms are :

    Asp.Net Web Forms
    Asp.Net MVC
    Asp.Net Web Form follow a traditional event-driven development model.
    Asp.Net MVC is a lightweight and follows MVC (Model, View, Controller) pattern based development, model.
    Asp.Net Web Form has server controls.
    Asp.Net MVC has HTML helpers.
    Asp.Net Web Form supports view state for state management at the client side.
    Asp.Net MVC does not support view state.
    Asp.Net Web Form has file-based URLs means file name exist in the URLs must have its physical existence.
    Asp.Net MVC has route-based URLs means URLs are divided into controllers and actions and moreover it is based on controller not on physical file.
    Asp.Net Web Form follows Web Forms Syntax
    Asp.Net MVC follow customizable syntax (Razor as default)
    In Asp.Net Web Form, Web Forms(ASPX) i.e. views are tightly coupled to Code behind(ASPX.CS) i.e. logic.
    In Asp.Net MVC, Views and logic are kept separately.
    Asp.Net Web Form has Master Pages for a consistent look and feels.
    Asp.Net MVC has Layouts for a consistent look and feels.
    Asp.Net Web Form has User Controls for code re-usability.
    Asp.Net MVC has Partial Views for code re-usability.
    Asp.Net Web Form has built-in data controls and best for rapid development with powerful data access.
    Asp.Net MVC is lightweight, provide full control over markup and support many features that allow fast & agile development. Hence it is best for developing an interactive web application with the latest web standards.
    Asp.Net Web Form is not Open Source.
    Asp.Net Web MVC is an Open Source.
  • Below are the events in an asp.net page life cycle :
    1) Page_PreInit
    2) Page_Init
    3) Page_InitComplete
    4) Page_PreLoad
    5) Page_Load
    6) Page_LoadComplete
    7) Page_PreRender
    8) Render

    ASP.NET goes through a series of stages in the life cycle of each page.
    Page request. The user requests a page. ASP.NET decides whether to compile it or serve it from a cache.
    Page Start. The Request and Response objects are created.
    Page Initialization. All page controls are initialized, and any themes are applied.
    Page Load. ASP.NET uses the view state and control state properties to set the control properties. Default values are set in the controls.
    Postback event handling. This event is triggered if the same page is loaded again.
    Rendering. ASP.NET saves the view state for the page and writes the output of rendering to the output stream. It happens just before the complete web page is sent to the user.
    Unload. The rendered page gets sent to the client. ASP.NET unloads page properties and performs cleanup. All unwanted objects are removed from memory.

  • Custom controls are basically compiled code, i.e., DLLs. These can be easily added to the toolbox, so it can be easily used across multiple projects using a drag-and-drop approach. These controls are comparatively hard to create.

    But User Controls (.ascx) are just like pages (.aspx). These are comparatively easy to create but tightly coupled with respect to User Interface and code. In order to use across multiple projects, we need to copy and paste to the other project as well.

  • It is a built-in state management technique to preserve the form data. In order to maintain the state between postbacks, ASP.NET provides a mechanism called view state. Hidden form fields are used to store the state of objects on client side and returned back to server in subsequent request (as postback occurs).

    Advantages:
    1) Ensures security as data is stored in an encrypted format.
    2) No server resources used.
    3) ViewState properties can be easily enabled or disabled.
    4) Developers can develop it at page level or control level as per need.
    Disadvantages:
    1) If a huge amount of data is stored, loading the page may take longer than required.
    2) Data doesn't transfer from one page to another (between pages).

  • In case of Response.Redirect, a new request is generated from client-side for redirected page. It's a kind of additional round trip. As new request is generated from client, so the new URL is visible to user in browser after redirection.

    While in case of Server.Transfer, a request is transferred from one page to another without making a round trip from client. For the end user, URL remains the same in browser even after transferring to another page.

  • It is also called as the application file for ASP.NET. It contains code that responds to session-level and application-level events raised by HTTP modules or ASP.NET.

    It’s a place to write code for Application-level events such as Application start, Application end, Session start and end, Application error, etc.

    There is a good list of events that are fired but following are few of the important events in Global.asax:
    Application_Init occurs in case of application initialization for the very first time.
    Application_Start fires on application start.
    Session_Start fires when a new user session starts.
    Application_Error occurs in case of an unhandled exception generated from application.
    Session_End fires when user session ends.
    Application_End fires when application ends or time out.

  • Session is an Server Side State Management Technique.
    A Session can store the value on the Server.
    It can support any type of object to be stored along with our own custom objects

    ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request.

    There are various modes for storing session state:
    InProc: The session state is stored in the memory on the web server. This is the default mode.
    Custom mode: you can specify a custom storage provider.
    Off mode: disables the session state.
    OutProc: There are two ways to handle this mode:
    StateServer: The session state is stored in a separate process known as ASP.net state service. The session state is retained even if the application server is restarted and is available to multiple Web servers.
    SQLServer: Session state is stored in a database, thereby preserving the session state even if the Web application is restarted. Session state can be accessed by multiple Web servers in a Web farm.

  • Authentication is the process of identifying users and Authrozation is the process of granting access to those users based on identity. Together authentication and authorization secures our web application.
    Authentication: who is the user?
    Authrozation: what rights the user has? What resource the user can access?

    There are four types of authentication available in ASP.NET:
    1. Anonymous Authentication: This allows the users to access the public area of the website, without prompting a user for a username or password.Internally uses default app pool account/IUSR to access.
    Anonymous Authentication can be disabled through web config file :
    <authorization> <deny users="?"/> </authorization>
    2. Windows Authentication: This authentication method uses built-in Windows security features to authenticate a user.If any websites contains private information Or perform task such as booking tickets and placing orders then the users need to be authenticated and authorized. Windows authentication identifies and authorizes users based on server's user list.Access to the resource on the server is then granted or denied based on user's account privileges.
    Window authentication is best suited for Intranet web applications.
    The main advantage of this authentication is that, the web application can use the same security scheme that applies to your corporate network.
    Add tag : <identity impersonate="true" />
    if you want to have application code executed using logged in user identity.
    3. Forms Authentication: Authenticates against a customized list of users or users in a database.

    if (FormsAuthentication.Authenticate(username, password)) { FormsAuthentication.RedirectFromLoginPage(username, chk_Rem_me.Checked); }
    4. Passport Authentication: Validates against Microsoft Passport service which is basically a centralized authentication service.

  • 1. Required field Validator : check for an input to a control.
    2. Range Validator : check for some range of values.The data types supported by the RangeValidator control are Integer, Double, String, Currency, and Date.
    3. Compare Validator : use if you need to make sure the values in two different controls matched?
    4. Custom Validator : If we want to add any custom validation to control ac to our need.
    <asp:TextBox runat="server" id="txtCustom" />
    <asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtCustom" onservervalidate="cusCustom_ServerValidate" errormessage="The text must be exactly 8 characters long!" />

    protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
    {
    if(e.Value.Length == 8)
    e.IsValid = true;
    else
    e.IsValid = false;
    }

    5. Regular expression Validator : This validator is used to validate the value of an input control against the pattern defined by a regular expression. It allows us to check and validate predictable sequences of characters like: e-mail address, telephone number etc.
    <asp:TextBox ID="username" runat="server"></asp:TextBox>
    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"ControlToValidate="username" ErrorMessage="Please enter valid email" ForeColor="Red"ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"> </asp:RegularExpressionValidator>

    6. Summary Validator :
    This validator is used to display list of all validation errors in the web form.
    It allows us to summarize the error messages at a single location.
    We can set DisplayMode property to display error messages as a list, bullet list or single paragraph.
    <asp:ValidationSummary ID="ValidationSummary1" runat="server" ForeColor="Red"/>

    The Page.Validate() method is used to force all the validation controls to run and to perform validation.

    Client-side validation is the best way to validate data of a web page. It reduces the network traffic and saves server resources.

  • The architecture of the.Net framework is based on the following key components
    1. Language : A variety of languages exists for .net framework. They are VB.net and C# etc. These can be used to develop web applications. There are more than 60 .NET programming languages.
    2. Library : The .NET Framework includes a set of standard class libraries also called Framework Class Libraries. The most common library used for web applications in .net is the Web library. The web library has all the necessary components used to develop.Net web-based applications.
    3. Common Language Runtime : The Common Language Infrastructure or CLI is a platform. .Net programs are executed on this platform. The CLR is used for performing key activities. Activities include Exception handling and Garbage collection.

    Net Framework is a platform that provides tools and technologies to develop Windows, Web and Enterprise applications. It mainly contains two components,
    1. Common Language Runtime (CLR)
    2. .Net Framework Class Library.

    Common Language Runtime (CLR) : .Net Framework provides runtime environment called Common Language Runtime (CLR).It provides an environment to run all the .Net Programs. The code which runs under the CLR is called as Managed Code. Programmers need not to worry on managing the memory if the programs are running under the CLR as it provides memory management and thread management.
    Programmatically, when our program needs memory, CLR allocates the memory for scope and de-allocates the memory if the scope is completed.
    Language Compilers (e.g. C#, VB.Net, J#) will convert the Code/Program to Microsoft Intermediate Language (MSIL) intern this will be converted to Native Code by CLR.

    .Net Framework Class Library (FCL/BCL) :
    This is also called as Base Class Library and it is common for all types of applications i.e. the way you access the Library Classes and Methods in VB.NET will be the same in C#, and it is common for all other languages in .NET.
    The following are different types of applications that can make use of .net class library.
    1. Windows Application.
    2. Console Application
    3. Web Application.
    4. XML Web Services.
    5. Windows Services.
    In short, developers just need to import the BCL in their language code and use its predefined methods and properties to implement common and complex functions like reading and writing to file, graphic rendering, database interaction, and XML document manipulation.

    Main components of CLR are :
    1. Common Language Specification (CLS)
    2. Common Type System (CTS)
    3. Garbage Collection (GC)
    4. Just In – Time Compiler (JIT)

    Common Language Specification (CLS):
    It is responsible for converting the different .NET programming language syntactical rules and regulations into CLR understandable format. Basically, it provides the Language Interoperability. Language Interoperability means to provide the execution support to other programming languages also in .NET framework.

    Language Interoperability can be achieved in two ways :
    Managed Code: The MSIL code which is managed by the CLR is known as the Managed Code. For managed code CLR provides three .NET facilities:
    a> CAS(Code Access Security)
    b> Exception Handling
    c> Automatic Memory Management.
    Unmanaged Code: Before .NET development the programming language like .COM Components & Win32 API do not generate the MSIL code. So these are not managed by CLR rather managed by Operating System.

    Common Type System (CTS): Every programming language has its own data type system, so CTS is responsible for understanding all the data type systems of .NET programming languages and converting them into CLR understandable format which will be a common format.
    There are 2 Types of CTS that every .NET programming language have :
    Value Types: Value Types will store the value directly into the memory location. These types work with stack mechanism only. CLR allows memory for these at Compile Time.
    Reference Types: Reference Types will contain a memory address of value because the reference types won’t store the variable value directly in memory. These types work with Heap mechanism. CLR allots memory for these at Runtime.

    Garbage Collector:
    It is used to provide the Automatic Memory Management feature. If there was no garbage collector, programmers would have to write the memory management codes which will be a kind of overhead on programmers.

    JIT(Just In Time Compiler):
    It is responsible for converting the CIL(Common Intermediate Language) into machine code or native code using the Common Language Runtime environment.

  • Managed code is the code which is managed by the CLR(Common Language Runtime) in .NET Framework.
    Whereas the Unmanaged code is the code which is directly executed by the operating system.
    Below are some important differences between the Managed code and Unmanaged code:

    Managed Code Unmanaged Code
    It is executed by managed runtime environment or managed by the CLR. It is executed directly by the operating system.
    It provides security to the application written in .NET Framework. It does not provide any security to the application.
    Memory buffer overflow does not occur. Memory buffer overflow may occur.
    It provide runtime services like Garbage Collection, exception handling, etc. It does not provide runtime services like Garbage Collection, exception handling, etc.
    The source code is complied in the intermideate language know as IL or MSIL or CIL. The source code direclty compile into native langugae.
    It does not provide low-level access to the prgrammer. It provide low-level access to the prgrammer.
  • Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM .

    Category Stack Memory Heap Memory
    What is Stack & Heap?
    It is an array of memory.

    It is a LIFO (Last In First Out) data structure.

    In it data can be added to and deleted only from the top of it.
    It is an area of memory where chunks are allocated to store certain kinds of data objects.
    In it data can be stored and removed in any order.
    Practical Scenario
     
    Value of variable storing in stack 
     
    Value of variable storing in heap 
    What goes on Stack & Heap? 
    "Things" declared with the following list of type declarations are Value Types
    (because they are from System.ValueType):
    bool, byte, char, decimal, double, enum, float, int, long, sbyte, short, struct, uint, ulong, ushort
    "Things" declared with following list of type declarations are Reference Types
    (and inherit from System.Object... except, of course, for object which is the System.Object object):
    class, interface, delegate, object, string
    Memory Allocation
    Memory allocation is Static
    Memory allocation is Dynamic
    How is it Stored?  It is stored Directly It is stored indirectly
    Is Variable Resized?  Variables can’t be Resized Variables can be Resized
    Access Speed  Its access is fast Its access is Slow
    How is Block Allocated?
    Its block allocation is reserved in LIFO.
    Most recently reserved block is always the next block to be freed.
    Its block allocation is free and done at any time
    Visibility or Accessibility It can be visible/accessible only to the Owner Thread It can be visible/accessible to all the threads
    In Recursion Calls? In recursion calls memory filled up quickly In recursion calls memory filled up slowly
    Used By? It can be used by one thread of execution It can be used by all the parts of the application
    StackOverflowException .NET Runtime throws exception “StackOverflowException” when stack space is exhausted -
    When wiped off?
    Local variables get wiped off once they lose the scope
    -
    Contains It contains values for Integral Types, Primitive Types and References to the Objects -
    Garbage Collector  -
    It is a special thread created by .NET runtime to monitor allocations of heap space.
    It only collects heap memory since objects are only created in heap
  • An Assembly is a basic building block of .Net Framework applications. It is basically a pre-compiled chunk of code that can be executed by the CLR. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An Assembly can be a DLL or exe depending upon the project that we choose.

    Assemblies are basically the following three types:
    1. Private Assembly
    2. Shared Assembly
    3. Satellite Assembly

    1. Private Assembly
    It is an assembly that is being used by a single application only. Suppose we have a project in which we refer to a DLL so when we build that project that DLL will be copied to the bin folder of our project. That DLL becomes a private assembly within our project. Generally, the DLLs that are meant for a specific project are private assemblies.

    1. Shared Assembly
    Assemblies that can be used in more than one project are known to be a shared assembly. Shared assemblies are generally installed in the GAC. Assemblies that are installed in the GAC are made available to all the .Net applications on that machine.

    3. Satellite Assembly
    A satellite assembly is a compiled library (DLL) that contains “localizable” resources specific to a given culture such as strings, bitmaps, etc.
    You are likely to use satellite assemblies when creating a multilingual UI application. They are used to deploy applications in multiple cultures, with 1 satellite assembly per culture (default behavior)

    A definition from MSDN says something like this: "A .NET Framework assembly containing resources specific to a given language. Using satellite assemblies, you can place the resources for different languages in different assemblies, and the correct assembly is loaded into memory only if the user elects to view the application in that language."

    GAC (Global Assembly Cache)
    GAC stands for Global Assembly Cache. It is a memory that is used to store the assemblies that are meant to be used by various applications.
    Every computer that has CLR installed must have a GAC. GAC is a location that can be seen at
    “C:\Windows\assembly”
    “C:\Windows\Microsoft.NET\assembly\GAC_MSIL”.

    Installing an assembly into the GAC
    1. Generating Strong Name through command : sn –k “Path where you want that key to be generated” . This will generate the unique key pair that we will use in our application.
    2. Now type the command sn –T “ClassLibrary.dll”. After typing this command you will get a public key token that indicates that your assembly is Strongly Named and it is ready to install in the GAC.
    3. gacutil –i "Name of the Class Library" by this, the Assembly is successfully installed on the system

    Detail links : Link1| Link2

  • The garbage collector (GC) manages the allocation and release of memory.
    The garbage collector serves as an automatic memory manager.
    Garbage collection occurs when one of the following conditions is true: The system has low physical memory. The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.
    1. You do not need to know how to allocate and release memory or manage the lifetime of the objects that use that memory.
    2. An allocation is made any time you declare an object with a “new” keyword or a value type is boxed. Allocations are typically very fast.
    3. When there isn’t enough memory to allocate an object, the GC must collect and dispose of garbage memory to make memory available for new allocations.
    This process is known as garbage collection.

    Garbage Collection in C# has the following advantages −
    1. You don’t need to free memory manually while developing your application.
    2. It also allocates objects on the managed heap efficiently.
    3. When objects are no longer used then it will reclaim those objects by clearing their memory, and keeps the memory available for future allocations.
    4.Managed objects automatically get clean content to start with, so their constructors do not have to initialize every data field.

    Finalize:
    .NET Garbage collector does almost all clean up activity for your objects. But unmanaged resources (ex: - Windows API created objects, File, Database connection objects, COM objects etc) is outside the scope of .NET framework we have to explicitly clean our resources. For these types of objects .NET framework provides Object.Finalize method which can be overridden and clean up code for unmanaged resources can be put in this
    In Simple terms -The Finalize method is used to perform cleanup operations on unmanaged resources held by an object. It puts an object in the finalization queue. The Object will then be collected by the garbage collector ready to be cleaned up.
    Dispose:
    This is the best way we do clean our unallocated resources and yes not to forget we do not get the hit of running the Garbage collector twice.
    Collect:
    System.GC.Collect() forces garbage collector to run.This is not recommended but can be used if situations arises.

  • The components of ADO.Net are Dataset, Data Reader, Data Adaptor, Command, connection.

    1. Dataset :- The DataSet class in ADO.Net operates in an entirely disconnected nature, are used to get and store data in a C# application. DataSet is an in-memory representation of a collection of Database objects including related tables, constraints, and relationships among the tables.
    The biggest drawbacks of DataSet is speed because it is a high resource consuming process. It carrying considerable overhead because of related tables, constraints, and relationships among the tables. If you need forward only access to query results then DataReader is the best choice because in this scenario it is fastest way to go.
    No need to manually open and close connection in code.
    2. Data Reader :- DataReader is a connection oriented service. The data is available as long as the connection with database exists.You need to open and close the connecton manually in code.
    The ADO.NET DataReader is used to retrieve read-only (cannot update data back to a datasource) and forward-only (cannot read backward/random) data from a database.
    Using of a DataReader increases application performance and reduces system overheads. This is due to one row at a time is stored in memory.
    You create a DataReader by calling Command.ExecuteReader after creating an instance of the Command object.
    3. Data Adaptor :- DataAdapter acts as a bridge between a DataSet and a data source for retrieving and saving data. DataAdapter helps mapping the data in the DataSet to match the data in the data source.
    4. Command :- The ADO Command object is used to execute a single query against a database. The query can perform actions like creating, adding, retrieving, deleting or updating records.
    5. Connection :- The ADO Connection Object is used to create an open connection to a data source. Through this connection, you can access and manipulate a database.

    Data Set code Demo :
    string SQLquery = "SELECT CustomerID, CompanyName FROM dbo.Customers";
    // create DataSet that will hold your Tables/data
    DataSet ds = new DataSet("CustomerDataSet");
    //Create SqlDataAdapter which acts as bridge to put the data in DataSet,(data is table available by executing your SQL query)
    SqlDataAdapter myAdapter = new SqlDataAdapter(SQLquery, conn);
    //fill the dataset with the data by some name say "CustomersTable"
    myAdapter.Fill(ds,"CustomersTable");

    Data Reader code Demo :
    //opening connection is must
    conn.open();
    string SQLquery = "SELECT CustomerID, CompanyName FROM dbo.Customers";
    SqlCommand cmd = new SqlCommand(SQLquery, conn);
    // Call ExecuteReader to return a DataReader
    SqlDataReader myReader = cmd.ExecuteReader();
    //The Read method of the DataReader object is used to obtain a row from the results of the executed query.
    while(myReader.Read())
    {
    Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
    } //Once you're done with the data reader, call the Close method to close a data reader:
    myReader.Close();
    //close the connection
    conn.close();

    ExecuteScalar and ExecuteNonQuery :
    ExecuteScalar returns output value where as ExecuteNonQuery does not return any value but the number of rows affected by the query.
    ExecuteScalar used for fetching a single value and ExecuteNonQuery used to execute Insert and Update statements.

  • A cookie is a part of text that stores user-specific data. Cookies are stored by the browser in a user's hard drive and used whenever the user requests for a particular page. Cookies help in improving user experience and loading pages faster based on the date and time information stored as part of the data. In ASP, cookies can be created as well as retrieved. There are two types of cookies in ASP – persist, non-persist.

    Session Cookie Or Non-persistent - Resides on the client machine for a single session until the user does not log out.

    Persistent Cookie - Resides on a user's machine for a period specified for its expiry, such as 10 days, one month, and never.

    string NewKey = DateTime.Now.Ticks.ToString("x");
    string date = DateTime.Now.ToString();
    HttpCookie myCookie = HttpContext.Current.Request.Cookies["fKey"]; // get cookie
    if (myCookie == null)
    {
    myCookie = new HttpCookie("fKey");
    myCookie.Values.Add("Important_ID", NewKey);

    //set cookie expiry date-time. Made it to last for next 12 hours.
    myCookie.Expires = DateTime.Now.AddYears(10);
    //Most important, write the cookie to client.
    HttpContext.Current.Response.Cookies.Add(myCookie);
    }

  • To Create globalized application we need following namespaces :

    System.Globalization & System.Resources

  • The Major built-in objects in ASP.net are :
    1. Application
    2. Request
    3. Response
    4. Server
    5. Session
    6. Context
    7. Trace

  • The Page.Validate() method is used to force all the validation controls to run and to perform validation.

  • Boxing is assigning a value type to reference type variable.

    Unboxing is reverse of boxing ie. Assigning reference type variable to value type variable.

    In boxing, the value stored on the stack is copied to the object stored on heap memory, whereas unboxing is the opposite. In Unboxing, the object's value stored on the heap memory is copied to the value type stored on stack.

    Boxing
    The process of Converting a Value Type (char, int etc.) to a Reference Type(object) is called Boxing.
    Boxing is implicit conversion process in which object type (super type) is used.
    The Value type is always stored in Stack. The Referenced Type is stored in Heap.

    int num = 23; // 23 will assigned to num
    Object Obj = num; // Boxing

    Unboxing
    The process of converting reference type into the value type is known as Unboxing.
    It is explicit conversion process.

    int num = 23; // value type is int and assigned value 23
    Object Obj = num; // Boxing
    int i = (int)Obj; // Unboxing

  • Roslyn is the name of the compiler used by .NET Framework.

  • <asp:Login>: Provides a standard login capability that allows the users to enter their credentials
    <asp:LoginName>: Allows you to display the name of the logged-in user
    <asp:LoginStatus>: Displays whether the user is authenticated or not
    <asp:LoginView>: Provides various login views depending on the selected template
    <asp:PasswordRecovery>: email the users their lost password

  • Passport authentication is a centralized authentication service provided by Microsoft. The . NET Passport single sign-in service. When we use passport authentication then user authentication in your application is managed by Microsoft's passport service for which they charge.

    It is cookie based.
    User request secure page, and If no cookie, user will directed to passport.com
    Once authneticated, redirected to orignal request.

    Some advantages are :
    All the websites can be accessed using single login credentials. So no need to remember login credentials for each web site.
    Users can maintain his/ her information in a single location.
    Some cons are : Cost etc as Microsoft charges for this.

  • We can specify the theme in web.config file. Below is the code example to apply theme:

                                                            <configuration>
    
                                                            <system.web>
    
                                                            <pages theme="Windows7" />
    
                                                            </system.web>
    
                                                            </configuration>
                                                        
  • Web services are software programs that use XML to exchange data with other software through commonly used internet protocols. We can communicate with any object over the internet using web service.
    Web services are language-independent, platform-independent, protocol-independent, self-describing and programmable.

    Unlike web applications, web services are designed to communicate with other programs, rather than directly with users.

    While web services can provide data in a number of different formats, XML and JSON are the most common. These standard text-based formats can be easily recognized and parsed by another program that receives the data. The most common web service protocol – SOAP (Simple Object Access Protocol) – simply adds a header to each XML message before it is transferred over HTTP.

    HTTP Protocol is used to call a web service. Web services have file extension .asmx

  • Role Based Security used to implement security based on roles assigned to user groups in the organization.
    Then we can allow or deny users based on their role in the organization. Windows defines several built-in groups, including Administrators, Users, and Guests.

    < authorization >
    < allow roles="Domain_Name\Administrators" / > < !-- Allow Administrators in domain. -- >
    < deny users="*" / > < !-- Deny anyone else. -- >
    < /authorization >

  • Web.config : It is a configuration file, which is used in web application and it can be an ASP.NET project or MVC project. Some project contains multiple web.config file inside the same project but with different folder. They have their unique benefits. You can create several web.config file in each folder with their unique benefits as per your project requirement.
    It is used to store the application level configuration. Sometimes it inherits the setting from the machine.config. It parses at runtime, means if you make any changes then web application will load all the settings in the config file. You don’t need to create a web.config file because it is auto generated when you create a new web application. If you want to create a web.config manually you can create it.

    App.config : It is also a special type of configuration file which is basically used with Windows Services, Windows application, Console Apps or it can be WPF application or any others.
    It parses at compile time; it means if you edit the app.config when program is running, then you need to restart the application to reload the configuration setting into the program.
    When you run the application which contains the app.config, at the time of compilation a copy of app.config with different name moves into build folder for running the application, So that's why we need to restart the program if any changes made in app.config.

    Machine.config : It is a special type of configuration file which creates into the OS when you install visual studio. This stores machine level configuration setting. Only one machine.config file exists into the system and it stores highest level of configuration settings.
    Machine.config settings apply to all web applications which is residing on the server. The setting of machine.config can be overridden by web.config’s settings. If your system does not contain the machine.config then you cannot execute the application.

  • It is an optional file and is also called as the application file for ASP.NET. It contains code that responds to session-level and application-level events raised by HTTP modules or ASP.NET.

    Application_Start
    Application_End
    Application_AcquireRequestState
    Application_AuthenticateRequest
    Application_AuthorizeRequest
    Application_BeginRequest
    Application_Disposed
    Application_EndRequest
    Application_Error
    Application_PostRequestHandlerExecute
    Application_PreRequestHandlerExecute
    Application_PreSendRequestContent
    Application_PreSendRequestHeaders
    Application_ReleaseRequestState
    Application_ResolveRequestCache
    Application_UpdateRequestCache

  • We can SetNoStore on HttpCachePolicy object exposed by the Response object's Cache property:

    Response.Cache.SetNoStore ();
    Response.Write (DateTime.Now.ToLongTimeString ());

  • Caching is a technique of storing frequently used data/information in memory, so that, when the same data/information is needed next time, it could be directly retrieved from the memory instead of being generated by the application.

    When the application accesses data from Cache (i.e. in-memory) instead of fetching it from the original data store (maybe a database), it definitely improves performance. But Caching benefits are not limited only to performance; it also improves application Scalability and Availability.

    Caching is extremely important for performance boosting in ASP.NET, as the pages and controls are dynamically generated here. It is especially important for data related transactions, as these are expensive in terms of response time.

    Caching places frequently used data in quickly accessed media such as the random access memory of the computer. The ASP.NET runtime includes a key-value map of CLR objects called cache. This resides with the application and is available via the HttpContext and System.Web.UI.Page.

    Types of Caching :

    ASP.NET has 3 kinds of caching :
    1. Output Caching - stores a copy of the finally rendered HTML pages,
    2. Fragment Caching - when you need to cache only a subset of a page.
    3. Data Caching - caching data from a data source.

    Page Output Caching
    Page Output Caching is used to fetch information or data at page level . For output caching, an OutputCache directive can be added at the top of the .aspx page , specifying the duration (in seconds) that the page should be cached. <%@ OutputCache Duration="15" VaryByParam="None" %>
    System.Web.HttpCachePolicy

    Page Fragment Caching
    ASP.NET provides a mechanism for caching portions of pages, called page fragment caching . For example: user control. To cache a portion of a page, you must first encapsulate the portion of the page you want to cache into a user control . In the user control source file, add an OutputCache directive specifying the Duration and VaryByParam attributes. When that user control is loaded into a page at runtime , it is cached, and all subsequent pages that reference that same user control will retrieve it from the cache.

    Data Caching
    Data Caching is used to fetch the information of an application quickly based on the requirements. Cache object is just like application object which can be access anywhere in the application. The lifetime of the cache is equivalent to the lifetime of the application. Caching data can dramatically improve the performance of an application by reducing database contention and round-trips .
    using System.Web.Caching
    if (Cache["Employee"] == null)
    {
    Cache["Employee"] = dtEmployee;
    }
    else{
    GridView1.DataSource = (DataTable)Cache["Employee"];
    }

  • Yes, also we can have multiple web config files for an asp.net application.

  • RedirectPermanent Performs a permanent redirection from the requested URL to the specified URL. Once the redirection is done, it also returns 301 Moved Permanently responses.

    RedirectPermanent is used in case if we redirect website from http to https, If need to redirect users to some new developed resource.

  • ASP.NET MVC is a web application framework for the .NET Platform used for building full stack web applications using the Model-View-Controller pattern. It is an architectural pattern that seperates an application into three main logical components : model, view and controller.

    It supports seperation of concerns, since model describe the data, view represtens the UI and controller manage the presentation logic.

  • In strong typing, the data types of variable are checked at compile time. On the other hand, in case of weak typing the variable data types are checked at runtime. .NET languages incorporate strong typing.

    In case of strong typing, there is no chance of compilation error. Scripts use weak typing and hence issues arises at runtime.

    Every variable in .NET should have a type associated and the value assigned to the variable should match its type. If these rules are violated then compile time error will be displayed.

  • The first version of the .Net framework was released in the year 2002. The version was called .Net framework 1.0. The .Net framework has come a long way since then, and the current version is 4.7.1.

    Version .NET Framework Visual Studio Important Features
    C# 1.0 .NET Framework 1.0/1.1 Visual Studio .NET 2002 First release of C#
    C# 2.0 .NET Framework 2.0 Visual Studio 2005
    • Generics
    • Partial types
    • Anonymous methods
    • Nullable types
    • Iterators
    • Covariance and contravariance
    C# 3.0 .NET Framework 3.0\3.5 Visual Studio 2008
    • Auto-implemented properties
    • Anonymous types
    • Query expressions
    • Lambda expression
    • Expression trees
    • Extension methods
    C# 4.0 .NET Framework 4.0 Visual Studio 2010
    • Dynamic binding
    • Named/optional arguments
    • Generic covariant and contravariant
    • Embedded interop types
    C# 5.0 .NET Framework 4.5 Visual Studio 2012/2013
    • Asynchronous members
    • Caller info attributes
    C# 6.0 .NET Framework 4.6 Visual Studio 2013/2015
    • Static imports
    • Exception filters
    • Property initializers
    • Expression bodied members
    • Null propagator
    • String interpolation
    • nameof operator
    • Dictionary initializer
    C# 7.0 .NET Core Visual Studio 2017
    • Improved performance and productivity
    • Azure Support
    • AI Support
    • Game development
    • Cross platform
    • Mobile App Development
    • Window App Development
  • The Two Step Process :
    1. ASP.NET creates an environment which can process the request. In other words, it creates the application object, request, response and context objects to process the request.
    2. Once the environment is created, the request is processed through a series of events which is processed by using modules, handlers and page objects. To keep it short, let's name this step as MHPM (Module, handler, page and Module event)

    Creation of ASP.NET Environment

    Step 1: The user sends a request to IIS. IIS first checks which ISAPI extension can serve this request. Depending on file extension the request is processed. For instance, if the page is an ‘.ASPX page’, then it will be passed to ‘aspnet_isapi.dll’ for processing.

    Step 2: If this is the first request to the website, then a class called as ‘ApplicationManager’ creates an application domain where the website can run. As we all know, the application domain creates isolation between two web applications hosted on the same IIS. So in case there is an issue in one app domain, it does not affect the other app domain.

    Step 3: The newly created application domain creates hosting environment, i.e. the ‘HttpRuntime’ object. Once the hosting environment is created, the necessary core ASP.NET objects like ‘HttpContext’ , ‘HttpRequest’ and ‘HttpResponse’ objects are created.

    Step 4: Once all the core ASP.NET objects are created, ‘HttpApplication’ object is created to serve the request. In case you have a ‘global.asax’ file in your system, then the object of the ‘global.asax’ file will be created. Please note global.asax file inherits from ‘HttpApplication’ class.
    Note: The first time an ASP.NET page is attached to an application, a new instance of ‘HttpApplication’ is created. Said and done to maximize performance, HttpApplication instances might be reused for multiple requests.

    Step 5: The HttpApplication object is then assigned to the core ASP.NET objects to process the page.

    Step 6: HttpApplication then starts processing the request by HTTP module events, handlers and page events. It fires the MHPM event for request processing.

    More detail here..

  • 1. Application Domain is an ASP.NET concept which provides isolation for each ASP.NET application. Application Pool is an IIS concept which also provides isolation but at the process level.
    2. Application Domain is available only for ASP.NET applications. Application Pool is available for both ASP.NET and non-ASP.NET applications.
    3. Each ASP.NET application has its own Application Domain. One Application Pool can be shared by more than one applicaton.
    4. You do not have much control on creating an Application Domain for your application. You can configure the Application Pool using the IIS manager.
    5. You can edit and save the web.config file to recreate the Application Domain. You can recycle the Application Pool in the IIS manager.

    An Appdomain is a container within which ASPX runs and that Apppool is a process that starts the w3wp.exe worker process within which ASP applications run.

  • Tracing is an activity to follow execution path and display the diagnostic information related to a specific Asp.Net web page or application that is being executed on the web server. Tracing can be enabled at development environment as well as in the production environment. These information can help you to investigate errors or unwanted results while ASP.NET processes a page request. You can view trace information at the bottom of individual pages and also you can use the trace viewer to view these trace information that is collected and cached by ASP.NET when tracing is enabled.

    The tracing data is organized into a set of tables by ASP.NET. In Asp.Net Tracing is disabled by default. Trace statements are executed and shown only when tracing is enabled. You can enabled tracing in two levels.

    1. Page Leve Tracing : achieved through @ Page directive.

    2. Application Level Tracing : achieved through Web.config file setting

  • ASP.NET Web API is used purely for building backend web APIs which can be used by an array of clients, from the web to desktop to mobile. It forms the server component in the RESTful (Representational State Transfer) architecture.

    The ASP.NET Web API is an extensible framework for building HTTP based services that can be accessed in different applications on different platforms such as web, windows, mobile etc. It works more or less the same way as ASP.NET MVC web application except that it sends data as a response instead of html view.

  • If one intends to build a server component that can be easily utilized by an array of clients then ASP.NET Web API is the way to go. If, however, the project is purely going to be used as a web application, then ASP.NET MVC is a more appropriate choice.

  • In ASP.NET, you can create resource files that have different scope. You can create resource files that are global, which means that you can read the resource file from any page or code that is in the Web site. You can also create local resource files, which store resources for a single ASP.NET Web page (. aspx file).

    Local Resources Global Resources
    A local resource can only be accessed by the page that created it. Accessible by all pages.
    Difficult to maintain when the website has a lot of localized content as each page requires a resource file for each language. Only one file per language is required.
    Stored in the App_LocalResources folder. Stored in the App_GlobalResources folder.

    What is Globalization and Localization?
    Globalization is a process of designing applications intended for users of different languages across the Globe while Localization is a process of designing the application so that it can display contents in the language of the user.

    What is Language and Locale?
    Language means the broader category of spoken languages i.e. English, French, etc. Now English is spoken in United Kingdom as well as United States but these both countries have their own vocabulary of English language which is known as Locale. The Culture name for United Kingdom English is en-GB while for United States is en-US.

    Building a Multilingual ASP.Net website
    1. Add multiple resource file in App_GlobalResources folder
    //Set the Culture.
    Thread.CurrentThread.CurrentCulture = new CultureInfo(language);
    Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);

  • Yes , we can have multiple web.config file for an asp.net application.
    Why we need multiple web.config file?
    Suppose we are using form authentcation for our application and we have set authrozation element to deny users so that user can only access the login page before authenticating themselves into application.
    Now suppose we have a link of registration on our login page then user can't navigate to that registration page unless we create a registration folder and place registration.aspx there and a web.config with setting that applies to that folder's pages only eg:
    <authorization> <allow users="*"/> </authorization>
    Now user can navigate to registartion page despite we have set deny element in our main web.config file, as we have set allow users of authorization element in local web.config file.

  • “Internet Information Server,” IIS is a web server created by Microsoft.

    An application pool serves as a container for your applications in IIS. It's a collection of one or more URLs that can be served by a worker process, and it provides isolation: applications that run on one application pool are in no way affected by other applications that run on different application pools

    Because application pools allow a set of Web applications to share one or more similarly configured worker processes, they provide a convenient way to isolate a set of Web applications from other Web applications on the server computer

  • Server controls are the primary controls in ASP.NET and are categorized in the following groups:

    1. Validation controls: These controls validate user input by running the client-side script
    2. Data source controls: These are used to provide data binding for multiple data sources.
    3. Data view controls: These controls are used to view/display list and table data that is obtained from data sources
    4. Login and security controls: used for user authentication
    5. Master pages: used for giving a consistent interface and layout for the whole application
    6. Rich controls: These are used to implement special features like fileupload, calendar control, AdRotator etc.
    7. Navigation controls: help in navigation through menus, tree views and so on
    8. Personalization controls: used for personalization of page based on user information and preferences

  • HTTP modules and HTTP handlers are an integral part of the ASP.NET architecture. While a request is being processed, each request is processed by multiple HTTP modules (for example, the authentication module and the session module) and is then processed by a single HTTP handler.
    HTTPHandlers are used by ASP.NET web application server to handle specific requests based on extensions. HTTPHandlers run as processes in response to a request made to the ASP.NET website. It is a class that implements the System.Web.IHttpHandler interface. Any class that implements the IHttpHandler interface can perform as a target for the incoming HTTP requests.

    Diffrence
    HTTP handler is the process that runs in response to a request made to an ASP.NET Web application.
    HTTP modules let you examine incoming and outgoing requests and take action based on the request.

    An HttpModule is a component that is part of the ASP.NET request processing pipeline and is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request.

    An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes . HTTP modules let you examine incoming and outgoing requests and take action based on the request.

  • In the simplest terms, an ASP.NET HttpHandler is a class that implements the System.Web.IHttpHandler interface.

    ASP.NET HTTPHandlers are responsible for intercepting requests made to your ASP.NET web application server. They run as processes in response to a request made to the ASP.NET Site. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler.

    ASP.NET offers a few default HTTP handlers:
    1. Page Handler (.aspx): handles Web pages
    2. User Control Handler (.ascx): handles Web user control pages
    3. Web Service Handler (.asmx): handles Web service pages
    4. Trace Handler (trace.axd): handles trace functionality

    You can create your own custom HTTP handlers that render custom output to the browser.

    How to implement HTTPHandler ?
    Any class that implements the IHttpHandler interface can perform as a target for the incoming HTTP requests. The class should have a method ProcessRequest and a property called IsReusable.

        public class MyHandler :IHttpHandler
        {
            public bool IsReusable
            {
                get { return false; }
            }
            public void ProcessRequest(HttpContext context)
            {
    		    context.Response.Write("Handler Here....");
            }
        }
    
                                                        

    IsReusable property return either true or false in order to specify whether they can be reused and ProcessRequest is called to process http requests.

  • 1. Web Config conection string:
    <connectionStrings>
    <add name="strcon" connectionString="Data Source=DonetApp; Initial Catalog=dotnetDB; Persist Security Info=True;
    User ID=asif@123; Password=123@asif" providerName="System.Data.SqlClient"/>
    </connectionStrings>

  • Exe and DLLs are Assembly executable modules.
    An exe has it own address spaces in which it runs whereas dll runs inside some other memory space.

    Exe is an executable file. This runs the application for which it is designed. An Exe is generated when we build an application. Hence, the assemblies are loaded directly when we run an Exe. However, an Exe cannot be shared with the other applications.

    DLL stands for Dynamic Link Library. It is a library that consists of code that needs to be hidden. The code is encapsulated inside this library. An application can consist of many DLLs. These can be shared with the other applications as well.

    Other applications which share this DLL need not worry about the code intricacies as long as it is able to call the function on this DLL.

  • Internet Information Server (IIS) is one of the most popular web servers from Microsoft that is used to host and provide Internet-based services to ASP.NET and ASP Web applications. A web server is responsible for providing a response to requests that come from users. When a request comes from client to server IIS takes that request from users and process it and send response back to users.

    Internet Information Server (IIS) has it's own ASP.NET Process Engine to handle the ASP.NET request. The way you configure an ASP.NET application depends on what version of IIS the application is running on.

    Internet Information Server (IIS) includes a set of programs for building and administering Web applications, search engines, and support for writing Web-based applications that access databases such as SQL Server. With IIS, you can make your computer to work as a Web server and provides the functionality to develop and deploy ASP.NET Web applications on the server. You can also set security for a particular Website for specific Users and Computer in order to protect it from unauthorized access.

    IIS helps organizations to increase Web sites and application availability while lowering system administration and cost of deployment. IIS 7.5 supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP.

  • Basically, if you place a file with this name in the root of a web application directory, ASP.NET 2.0 will shut-down the application, unload the application domain from the server, and stop processing any new incoming requests for that application. ASP.NET will also then respond to all requests for dynamic pages in the application by sending back the content of the app_offline.htm file (for example: you might want to have a “site under construction” or “down for maintenance” message).

    "App_Offline.htm" feature in ASP.NET 2.0, which provides a super convenient way to bring down an ASP.NET application while you make changes to it (for example: updating a lot of content or making big changes to the site where you want to ensure that no users are accessing the application until all changes are done).

    The way app_offline.htm works is that you place this file in the root of the application. When ASP.NET sees it, it will shut-down the app-domain for the application (and not restart it for requests) and instead send back the contents of the app_offline.htm file in response to all new dynamic requests for the application. When you are done updating the site, just delete the file and it will come back online.

    Make sure that content of your app_offline.htm should not less than 512 bytes of content otherwise IE browser will show non HTTP-200 status code.Ie will recieve html and show generic code instead of html.
    Add some commented code in file to make it greator than 512 bytes and it will works in all browsers.

  • When we want to transport an object through a network, then we have to convert the object into a stream of bytes. The process of converting an object into a stream of bytes is called Serialization. For an object to be serializable, it should implement ISerialize Interface. De-serialization is the reverse process of creating an object from a stream of bytes.

Frequently Asked C# Questions

  • It is an object-oriented programing language developed by Microsoft in (2000), which runs under the .NET platform.
    C# is the primary language that is used to create .Net software applications.
    C# is widely used for developing web applications, desktop applications, web services, mobile apps, and games, etc. Now, C# can be run on Mac, Linux/Unix and Windows using .NET Core.

    Features :
    1. Open-source
    2. Object-oriented
    3. Simple, Flexible and scalable
    4. Type safe and Modern Programming language
    5. Component oriented and Structured programming language
    6. Rich Library and Fast Speed

    Evolution History

  • Methods dispose() and finalize() are the methods of C# which are invoked to free the unmanaged resources held by an object.

    The dispose() method is defined inside the interface IDisposable whereas, the method finalize() is defined inside the class object. The main difference between dispose() and finalize() is that the method dispose() has to be explicitly invoked by the user whereas, the method finalize() is invoked by the garbage collector, just before the object is destroyed.

    Finalize() : -
    Finalize() is called by the Garbage Collector to deallocate the memory for the unreferenced object.The Garbage Collector calls this method at some point after there are no longer valid references to that object in memory.Implemented through destructor.
    public class Demo{~Demo(){Console.WriteLine("Finalize called");}}

    Dispose() : -
    There are some resources like windows handles, database connections, network connections, files, etc. which cannot be collected by the Garbage Collector. If we want to explicitly release some specific objects then this is the best to implement IDisposable and override the Dispose() method of IDisposable interface.
    The Dispose() method is not called automatically and we must explicitly call it from a client application when an object is no longer needed. Dispose() can be called even if other references to the object are alive.
    public void Dispose(){ Dispose(true); GC.SuppressFinalize(this); }

    finally: -
    It is a block of code written to execute regardless of whether an exception is caught or not. The main purpose of finally block is to release the system resources.
    1. In C#, multiple finally blocks in the same program are not allowed.
    2. The finally block does not contain any return, continue, break statements because it does not allow controls to leave the finally block.
    3. You can also use finally block only with a try block means without a catch block but in this situation, no exceptions are handled.
    4. The finally block will be executed after the try and catch blocks, but before control transfers back to its origin.

  • "throw" maintains the full hierarchy in the stack trace and gives complete information about the exception occurred in the code.
    Whereas "throw ex" pretends that exceptions occurred on the line where "throw ex" was written and removes all the hierarchy above the method containing the "throw ex" expression.

  • In C#, Dictionary is a generic collection which is generally used to store key/value pairs. Dictionary is defined under System.Collection.Generics namespace. It is dynamic in nature means the size of the dictionary is growing according to the need.

    Dictionary<string, string> My_dict = new Dictionary<string, string>();
    // Adding key/value pairs in the Dictionary Using Add() method
    My_dict.Add("a.01", "C");
    My_dict.Add("a.02", "C++");
    My_dict.Add("a.03", "C#");
    foreach(KeyValuePair<string, string> element in My_dict)
    {
    Console.WriteLine("Key:- {0} and Value:- {1}", element.Key, element.Value);
    }

    A Hashtable (key/value pair) is used to create a collection which uses a hash table for storage.It is the non-generic type of collection which is defined in System.Collections namespace.

    Hashtable my_hashtable = new Hashtable();
    // Adding key/value pair in the hashtable Using Add() method
    my_hashtable.Add("A1", "Welcome");
    my_hashtable.Add("A2", "to");
    my_hashtable.Add("A3", "GeeksforGeeks");
    foreach(DictionaryEntry element in my_hashtable)
    {
    Console.WriteLine("Key:- {0} and Value:- {1} ", element.Key, element.Value);
    }

    Hashtable Dictionary
    A Hashtable is a non-generic collection. A Dictionary is a generic collection.
    Hashtable is defined under System.Collections namespace. Dictionary is defined under System.Collections.Generic namespace.
    In Hashtable, you can store key/value pairs of the same type or of the different type. In Dictionary, you can store key/value pairs of same type.
    In Hashtable, there is no need to specify the type of the key and value. In Dictionary, you must specify the type of key and value.
    The data retrieval is slower than Dictionary due to boxing/ unboxing. The data retrieval is faster than Hashtable due to no boxing/ unboxing.
    In Hashtable, if you try to access a key that doesn’t present in the given Hashtable, then it will give null values. In Dictionary, if you try to access a key that doesn’t present in the given Dictionary, then it will give error.
    It is thread safe. It is also thread safe but only for public static members.
    It doesn’t maintain the order of stored values. It always maintain the order of stored values.
  • StringBuilder is used to represent a mutable string of characters. Mutable means the string which can be changed. So String objects are immutable but StringBuilder is the mutable string type. It will not create a new modified instance of the current string object but do the modifications in the existing string object. The complete functionality of StringBuilder is provided by StringBuilder class which is present in System.Text namespace.

    Why String builder ?
    String class objects are immutable which means that if the user will modify any string object it will result into the creation of a new string object. It makes the use of string costly. So when the user needs the repetitive operations on the string then the need of StringBuilder come into existence. It provides the optimized way to deal with the repetitive and multiple string manipulation operations.

    // conversion from String object to StringBuilders
    StringBuilder sbl = new StringBuilder(str); sbl.Append("ForGeeks");

    StringBuilder sbdr = new StringBuilder("Builder");
    // conversion from StringBuilder object to String using ToString method
    String str1 = sbdr.ToString();

  • Value Type: A value type variable stores actual values. Values types are of two types - built-in(byte, short, int, long, float, double, decimal, char, bool) and user-defined (enum and struct). Value types are stored in a stack and derived from System.ValueType class.

    Reference Type: A reference type variable stores a reference to the actual value. Typically, a reference type contains a pointer to another memory location that stores the actual data. Reference types are of two types - built-in (dynamic, object, string) and user-defined (class, interface, delegate, array). Reference types are stored in a heap and derived from System. Object class.

  • Constant variables are declared and initialized at compile time. The value can't be changed afterward. Read-only is used only when we want to assign the value at run time.

    public class Const_V_Readonly
    {
    public const int I_CONST_VALUE = 2;
    public readonly int I_RO_VALUE;
    public Const_V_Readonly()
    {
    I_RO_VALUE = 3;
    }
    }

    A Static Readonly type variable's value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable's value can only be changed in the static constructor. And cannot be changed further. It can change only once at runtime.

    public class Variables{
    readonly static string str;
    readonly static string str1="pradeep";
    static Variables(){
    str=str1;
    str1="changed now";
    }

  • Namespace is a logical grouping of classes belongs to same functionality. So System.Web and System.Data are namespaces

    MSDN describe it as: Namespaces are heavily used in C# programming in two ways. First, the .NET Framework uses namespaces to organize its many classes Secondly, declaring your own namespaces can help control the scope of class and method names in larger programming projects.

    Assembly is chunk of (precompiled) code that can be executed by the .NET runtime environment. It contains one or more than one Namespaces. A .NET program consists of one or more assemblies.
    System.Web.dll and System.Data.dll are assemblies.

  • The static keyword is used to specify a static member, which means static members are common to all the objects and they do not tie to a specific object. This keyword can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.

    class MyClass
    {
    static int X = 10;
    int Y = 20;
    public static void Show()
    {
    Console.WriteLine(X);
    Console.WriteLine(Y); //error, since you can access only static members
    }
    }

    Key Points :
    1. If the static keyword is applied to a class, all the members of the class must be static.
    2. Static methods can only access static members of the same class. Static properties are used to get or set the value of static fields of a class.
    3. A static constructor can't be parameterized. Access modifiers cannot be applied on Static constructor, it is always a public default constructor which is used to initialize static fields of the class.

  • Ref and out keywords in C# are used to pass arguments within a method or function. Both indicate that an argument/parameter is passed by reference. By default parameters are passed to a method by value. By using these keywords (ref and out) we can pass a parameter by reference.

    The ref is a keyword in C# which is used for the passing the arguments by a reference. Or we can say that if any changes made in this argument in the method will reflect in that variable when the control return to the calling method. The ref parameter does not pass the property.

    The out is a keyword in C# which is used for the passing the arguments to methods as a reference type. It is generally used when a method returns multiple values. The out parameter does not pass the property.

    ref keyword out keyword
    It is necessary the parameters should initialize before it pass to ref. It is not necessary to initialize parameters before it pass to out.
    It is not necessary to initialize the value of a parameter before returning to the calling method. It is necessary to initialize the value of a parameter before returning to the calling method.
    The passing of value through ref parameter is useful when the called method also need to change the value of passed parameter. The declaring of parameter through out parameter is useful when a method return multiple values.
    When ref keyword is used the data may pass in bi-directional. When out keyword is used the data only passed in unidirectional.

    Both ref and out parameter treated same at compile-time but different at run-time.

  • The is operator returns true if the given object is of the same type, whereas the as operator returns the object when they are compatible with the given type. The is operator returns false if the given object is not of the same type, whereas the as operator returns null if the conversion is not possible.

    The difference between is and as operators are as follows:
    1. The is operator is used to check if the run-time type of an object is compatible with the given type or not whereas as operator is used to perform conversion between compatible reference types or Nullable types.
    2. The is operator is of boolean type whereas as operator is not of boolean type.
    3. The is operator returns true if the given object is of the same type whereas as operator returns the object when they are compatible with the given type.
    4. The is operator returns false if the given object is not of the same type whereas as operator return null if the conversion is not possible.
    5. The is operator is used for only reference, boxing, and unboxing conversions whereas as operator is used only for nullable, reference and boxing conversions

    P o1 = new P();
    // checking whether 'o1' is of type 'P'
    Console.WriteLine(o1 is P);

    object[] o = new object[2];
    o[1] = new Z();
    o[2] = "Hello";
    string str1 = o[0] as string; // returns null
    string str1 = o[1] as string; // returns Hello

  • Break statement breaks the loop. It makes the control of the program to exit the loop. Continue statement makes the control of the program to exit only the current iteration. It does not break the loop.

    You can use break statements in both switch and loop (for, while, and do-while ) statements.

    You can use continue statements only in the loop (for, while, do) statements.

  • A constructor is a member function in a class that has the same name as its class. The constructor is automatically invoked whenever an object class is created. It constructs the values of data members while initializing the class.

    It initializes the data members of a class when new object of class is created.

    Default Constructor
    A default constructor has no parameter. When a class has no constructor, a default constructor is served by the compiler to that class.

    Parameterized Constructor
    The parameterized constructor has one or more arguments and used to assign values to instance variables of the class.
    It is invoked with parameters that are passed to the class during object creation.

  • 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#.

    Sr.No. Class & Description and Useage
    1 ArrayList

    It represents ordered collection of an object that can be indexed individually.

    It is basically an alternative to an array. However, unlike array you can add and remove items from a list at a specified position using an index and the array resizes itself automatically. It also allows dynamic memory allocation, adding, searching and sorting items in the list.

    2 Hashtable

    It uses a key to access the elements in the collection.

    A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection.

    3 SortedList

    It uses a key as well as an index to access the items in a list.

    A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key , it is a Hashtable. The collection of items is always sorted by the key value.

    4 Stack

    It represents a last-in, first out collection of object.

    It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item.

    5 Queue

    It represents a first-in, first out collection of object.

    It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue and when you remove an item, it is called deque.

    6 BitArray

    It represents an array of the binary representation using the values 1 and 0.

    It is used when you need to store the bits but do not know the number of bits in advance. You can access items from the BitArray collection by using an integer index, which starts from zero.

  • Data Type Size Description
    int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647
    long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
    float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
    double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
    bool 1 bit Stores true or false values
    char 2 bytes Stores a single character/letter, surrounded by single quotes
    string 2 bytes per character Stores a sequence of characters, surrounded by double quotes

    // -------DATA TYPES ------- //
    sbyte myNum = 1; // Smallest range of integer numbers
    uint myNum = 3; // Only positive integer numbers
    short myNum = 4; // Short range of integer numbers
    int myNum = 5; // Integer (whole numbers)
    long myNum = 10; // Biggest range of integer numbers
    float myFloat = 1.2f; // Smallest range of floating point numbers
    double myDoubleNum = 5.99; // Big range of floating point numbers
    decimal myDecimalNum = 2.2M; // Biggest precision in floating point numbers
    char myLetter = 'D'; // Character
    string myString = "Hello!" // Strings
    bool myBool = true; // Boolean

  • Method parameter is one of the integral part of programming and it also applies with C# programming Language.
    We can categorize method parameters in various parts. Some of them are:
    1. Named Parameters (C# 4.0 and above) : - parameter is being passed by name so order does not matter.
    2. Ref Parameter (Passing Value Types by Reference)
    3. Out Parameters
    4. Default Parameters or Optional Arguments (C# 4.0 and above) :
    public int add(x,y=12,z=10){
    return x+y+z;
    }

    5. Dynamic parameter (dynamic keyword).
    6. Value parameter or Passing Value Types by Value (normal C# method param are value parameter)
    7. Params (params)
    public static void PrintPassedList(params string[] listtoPrint)
    {
    foreach(var item in listtoPrint)
    {
    WriteLine(item);
    }
    }

  • A static class cannot be instantiated using the new keyword. All methods in a static class must be static and can be called directly without instantiation.
    A "normal" class MUST be instantiated however any static methods in a "normal" class can be called without instantiation.
    Non static methods in a "normal" class cannot be called without first instantiating the containing class.

  • Explicit implementation is also used to resolve cases where two interfaces each declare different members of the same name such as a property and a method. To implement both interfaces, a class has to use explicit implementation either for the property P , or the method P , or both, to avoid a compiler error.

    Explicitly telling the compiler that a particular member belongs to that particular interface is called Explicit interface implementation.

    If two interface has same name method print and if we are implementing both interfaces then we should define those print method with the name of interface eg void I1.Print(){}, I2.Print(){}

  • Interfaces contain method signatures, properties, events etc. Interfaces are used so that one class or struct can implement multiple behaviors. C# doesn’t support the concept of Multiple Inheritance because of the ambiguity it causes. But a lot of real life objects inherit properties of more than just one type, therefore interfaces are used instead of extending classes. An Interface consists only of the signatures and not its implementation, therefore, any class or struct that implements it has to provide the implementation by overriding.

  • Supposee we have a public class Customer which have 3 private fields eg id,first_name and last_name and and 3 property to get set values of fields and one public method that getFullname() which return full name of customer.

    In above example Custome is a Type and an field, properties and methods are type members.

    So in general class, structs, enum, interfaces, delegates , tuples are called type and field, property, methods, constructors etc, that normaly reside in type are called Type members.

    In c# there are 5 diffrent access modifiers : public, private, protected, internal and protected internal

    Type members can have all access modifiers but types can have only 2 (public and internal)

  • A private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes cannot create instances of this class.

  • 1.IEnumerable exists in System.Collections Namespace.
    2.IQueryable exists in System. Linq Namespace.
    3.Both IEnumerable and IQueryable are forward collection.
    4.IEnumerable doesn’t support lazy loading
    5.IQueryable support lazy loading
    6.Querying data from a database, IEnumerable execute a select query on the server side, load data in-memory on a client-side and then filter data.
    7.Querying data from a database, IQueryable execute the select query on the server side with all filters.
    8.IEnumerable Extension methods take functional objects.
    9.IQueryable Extension methods take expression objects means expression tree.

  • C# indexers are usually known as smart arrays. A C# indexer is a class property that allows you to access a member variable of a class or struct using the features of an array. In C#, indexers are created using this keyword. Indexers in C# are applicable on both classes and structs.

    private string[] names = new string[10];
    public string this[int i]
    {
    get
    {
    return names[i];
    }
    set
    {
    names[i] = value;
    }
    }

  • C# supports tuples, which provides concise syntax to group multiple data elements in a lightweight data structure. You instantiate a tuple by declaring the types and names of the members between ( and ), as shown in the following example:

    (double Sum, int Count) t2 = (4.5, 3); Console.WriteLine($"Sum of {t2.Count} elements is {t2.Sum}.");

    // How to create a Typle
    Tuple<int, string, string> person = new Tuple <int, string, string>(1, "Steve", "Jobs");
    //extra examples
    var person = Tuple.Create(1, "Steve", "Jobs"); person.Item1; // returns 1 person.Item2; // returns "Steve" person.Item3; // returns "Jobs"

    var tupleList = new List<Tuple<int, string, string, string>>(); tupleList.Add(Tuple.Create(1, "Sefat Anam", "Dhaka Bangladesh", "0.1245345"));

  • Sealed class is used to define the inheritance level of a class.

    The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class.

    Some points to remember:
    1. A class, which restricts inheritance for security reason is declared sealed class.
    2. Sealed class is the last class in the hierarchy.
    3. Sealed class can be a derived class but can't be a base class.
    4. A sealed class cannot also be an abstract class. Because abstract class has to provide functionality and here we are restricting it to inherit.

    Sealed method :
    Sealed method is used to define the overriding level of a virtual method.

    Sealed keyword is always used with override keyword.

  • An enumeration is a set of named integer constants. An enumerated type is declared using the enum keyword.
    C# enumerations are value data type. In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance.

    enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

  • A partial class is a special feature of C#. It provides a special ability to implement the functionality of a single class into multiple files and all these files are combined into a single class file when the application is compiled. A partial class is created by using a partial keyword. This keyword is also useful to split the functionality of methods, interfaces, or structure into multiple files.

    Important Points :
    1. The partial modifier can only present instantly before the keywords like struct, class, and interface.
    2. Every part of the partial class definition should be in the same assembly and namespace, but you can use a different source file name.
    3. Every part of the partial class definition should have the same accessibility as private, protected, etc.
    4. If any part of the partial class is declared as an abstract, sealed, or base, then the whole class is declared of the same type.

  • An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators, assemblies etc. in your program. You can add declarative information to a program by using an attribute. A declarative tag is depicted by square ([ ]) brackets placed above the element it is used for.

    Attributes are used for adding metadata, such as compiler instruction and other information such as comments, description, methods and classes to a program. The .Net Framework provides two types of attributes: the pre-defined attributes and custom built attributes.

    [Serializable] //<-A class marking attribute marking the your class to do the work of getting ready your class for serlization so you dont have to.
    public class SomeAPIClass
    [Conditional("DEBUG")]
    [Obsolete("Don't use OldMethod, use NewMethod instead", true)]

    Fields are the instance members of the class eg private first_name;

    Property are used to get and set values of the data members of the class eg fields public first_name{get,set}

  • A thread is an independent execution path, able to run simultaneously with other threads. A C# client program (Console, WPF, or Windows Forms) starts in a single thread created automatically by the CLR and operating system (the “main” thread), and is made multithreaded by creating additional threads.

    Multi-threading is the most useful feature of C# which allows concurrent programming of two or more parts of the program for maximizing the utilization of the CPU. Each part of a program is called Thread. So, in other words, threads are lightweight processes within a process. C# supports two types of threads are as follows :
    1. Foreground Thread :
    A thread which keeps on running to complete its work even if the Main thread leaves its process, this type of thread is known as foreground thread. Foreground thread does not care whether the main thread is alive or not, it completes only when it finishes its assigned work. Or in other words, the life of the foreground thread does not depend upon the main thread.
    2. Background Thread :
    A thread which leaves its process when the Main method leaves its process, these types of the thread are known as the background threads. Or in other words, the life of the background thread depends upon the life of the main thread. If the main thread finishes its process, then background thread also ends its process.

    // Creating and initializing thread
    Thread thr = new Thread(mythread);
    // Name of the thread is Mythread
    thr.Name = "Mythread";
    thr.Start();
    // IsBackground is the property of Thread
    // which allows thread to run in the background
    thr.IsBackground = true;

  • An access modifier, which is used to set the access level/visibility for classes, fields, methods and properties.

    Modifier Description
    public The code is accessible for all classes
    private The code is only accessible within the same class
    protected The code is accessible within the same class, or in a class that is inherited from that class.
    internal The code is only accessible within its own assembly, but not from another assembly.
  • In C#, inheritance is a process in which one object acquires all the properties and behaviors of its parent object automatically. ... In C#, the class which inherits the members of another class is called derived class and the class whose members are inherited is called base class.

    Inheritance is used for code reusablity.

    class parent_class
    {
    // fields
    // properties
    // methods
    }
    class child_class : parent_class
    {
    //Will simply move Data and Methods from the parent_class to the child class.
    }

  • Single name & multiple meaning
    Polymorphism means assigning a single name but there can be multiple behaviors. It means the name of the function is same but its definitions are different.

    Types :
    Compile time polymorphism is achieved by method overloading and operator overloading in C#. It is also known as static binding or early binding. Runtime polymorphism in achieved by method overriding which is also known as dynamic binding or late binding.

  • A class is a template for creating objects in program whereas the object is an instance of a class. A class is a logical entity while object is a physical entity. A class does not allocate memory space on the other hand object allocates memory space. ... Classes doesn't have any values, whereas objects have its own values.

    Constructors is a special method of the class that is automatically invoked when an instance of the class is created is called a constructor. The main use of constructors is to initialize the private fields of the class while creating an instance for the class. When you have not created a constructor in the class, the compiler will automatically create a default constructor of the class. The default constructor initializes all numeric fields in the class to zero and all string and object fields to null.

    Destructors are just the opposite of constructors. It is a special method of the class that is invoked when a class object goes out of scope. Similar to a constructor, a destructor name is also exactly the same as that of the class name but with a prefix of “ ~ ” (tilde).

  • In C#, struct is the value type data type that represents data structures. ... struct can be used to hold small data values that do not require inheritance, e.g. coordinate points, key-value pairs, and complex data structure.

    public struct Coords
    {
    public Coords(double x, double y)
    {
    X = x;
    Y = y;
    }
    public double X { get; }
    public double Y { get; }
    public override string ToString() => $"({X}, {Y})";
    }

  • Interface in C# is a blueprint of a class. It is like abstract class because all the methods which are declared inside the interface are abstract methods. It cannot have method body and cannot be instantiated. It is used to achieve multiple inheritance which can't be achieved by class.

    An Interface is a pure abstract class
    The class who implements a interface defines all its methods.

  • Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).

    Data abstraction is the process of hiding certain details and showing only essential information to the user.
    Abstraction can be achieved with either abstract classes or interfaces

    When to use : To achieve security - hide certain details and only show the important details of an object.

    The abstract keyword is used for classes and methods:
    Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
    Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the derived class (inherited from).
    An abstract class can have both abstract and regular methods:

  • A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance

    Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword. You can declare a delegate that can appear on its own or even nested inside a class. There are three steps in using delegates. These include declaration, instantiation, and invocation.

    public delegate int PerformCalculation(int x, int y);

  • Exception Handling in C# is a process to handle runtime errors. We perform exception handling so that normal flow of the application can be maintained even after runtime errors. In C#, exception is an event or object which is thrown at runtime. All exceptions the derived from System. Exception class.

    C# exception handling is built upon four keywords: try, catch, finally, and throw. try − A try block identifies a block of code for which particular exceptions is activated. catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem.

  • Reflection is the process of describing the metadata of types, methods and fields in a code. The namespace System.Reflection enables you to obtain data about the loaded assemblies, the elements within them like classes, methods and value types.

  • Generic means the general form, not specific. In C#, generic means not specific to a particular data type. C# allows you to define generic classes, interfaces, abstract classes, fields, methods, static methods, properties, events, delegates, and operators using the type parameter and without the specific data type.

    Generics allow you to write a class or method that can work with any data type.

    Generics are used to make reusable code classes to decrease the code redundancy, increase type safety, and performance. Using generics, we can create collection classes. To create generic collection, System.Collections.Generic namespace should be used instead of classes such as ArrayList in the System.Collections namespace. Generics promotes the usage of parameterized types.

  • Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

    public static class MyExtensions
    {
    //use the this keyword before an argument
    public static int WordCount(this String str)
    {
    return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
    }
    }

  • Design Patterns in the object-oriented world is a reusable solution to common software design problems that occur repeatedly in real-world application development. It is a template or description of how to solve problems that can be used in many situations. "A pattern is a recurring solution to a problem in a context

    Singleton design pattern in C# is one of the most common design patterns is software design. In singleton design pattern ensures a class has only one instance in the program and provides a global point of access to it. A singleton is a class that only allows a single instance of itself to be created and usually gives simple access to that instance.

  • The process of invoking a sequence of constructors upon initialization of a class object is called constructor chaining. Constructor chaining is useful when you want to invoke multiple constructors, one after another, by initializing only one instance.

    The real purpose of Constructor Chaining is that you can pass parameters through a bunch of different constructors, but only have the initialization done in a single place. This allows you to maintain your initializations from a single location, while providing multiple constructors to the user.

  • SOURCE CODE -----.NET COMLIPER------> BYTE CODE (MSIL + META DATA)

    BYTE CODE (MSIL + META DATA) ----- Just-In-Time (JIT) compiler------> NATIVE CODE

  • A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value. The Nullable types are instances of System. Nullable<T> struct.

  • Asynchronous programming in C# is an efficient approach towards activities blocked or access is delayed. If an activity is blocked like this in a synchronous process, then the complete application waits and it takes more time. ... Asynchronous methods defined using the async keyword are called async methods.

    When to use Async/Await
    1. I/O-bound work: Your code will be waiting for something, such as data from a database, reading a file, a call to a web service. In this case you should use Async/Await, but not use the Task Parallel Library.
    2. CPU-bound work: Your code will be performing a complex computation.

  • In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time. The dynamic type variable is created using dynamic keyword.

    dynamic value = 123;

  • Var Dynamic
    It is introduced in C# 3.0. It is introduced in C# 4.0
    The variables are declared using var keyword are statically typed. The variables are declared using dynamic keyword are dynamically typed.
    The type of the variable is decided by the compiler at compile time. The type of the variable is decided by the compiler at run time.
    The variable of this type should be initialized at the time of declaration. So that the compiler will decide the type of the variable according to the value it initialized. The variable of this type need not be initialized at the time of declaration. Because the compiler does not know the type of the variable at compile time.
    If the variable does not initialized it throw an error. If the variable does not initialized it will not throw an error.
    It support intelliSense in visual studio. It does not support intelliSense in visual studio
    var myvalue = 10; // statement 1
    myvalue = “abc”; // statement 2
    Here the compiler will throw an error because the compiler has already decided the type of the myvalue variable using statement 1 that is an integer type. When you try to assign a string to myvalue variable, then the compiler will give an error because it violating safety rule type.
    dynamic myvalue = 10; // statement 1
    myvalue = “abc”; // statement 2
    Here, the compiler will not throw an error though the type of the myvalue is an integer. When you assign a string to myvalue it recreates the type of the myvalue and accepts string without any error.
    It cannot be used for properties or returning values from the function. It can only used as a local variable in function. It can be used for properties or returning values from the function.
  • The term File Handling refers to the various operations like creating the file, reading from the file, writing to the file, appending the file, etc.

    A stream is a sequence of bytes which is used for communication. Two stream can be formed from file one is input stream which is used to read the file and another is output stream is used to write in the file. In C#, System.IO namespace contains classes which handle input and output streams and provide information about file and directory structure.

  • A thread in C# at any point of time exists in any one of the following states. A thread lies only in one of the shown states at any instant:
    1.Unstarted
    2.Runnable
    3.Running
    4.Not Runnable
    5.Dead

    Thread class provides different types of methods to implement the states of the threads. 1. Sleep() method is used to temporarily suspend the current execution of the thread for specified milliseconds, so that other threads can get the chance to start the execution, or may get the CPU for execution.
    2. Join() method is used to make all the calling thread to wait until the main thread, i.e. joined thread complete its work.
    3. Abort() method is used to abort the thread.
    4. Suspend() method is called to suspend the thread.
    5. Resume() method is called to resume the suspended thread.
    6. Start() method is used to send a thread into runnable State.

Tricky C# Questions

  • Why c# does not supports multiple inheritances?
    One of the main reason behind this is the “diamond problem”.

    The "diamond problem" is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a method in A that B and C have overridden, and D does not override it, then which class of the method does D inherit: that of B, or that of C? So this is an ambiguity problem in multiple inheritances in c#. So that c# does not support multiple inheritances. It also called an ambiguity problem in c#.

    We can resolve the diamond problem by using Interface in c#.

    Interfaces guarantee that a given set of methods will be implemented. The interface does not concern itself on how will the code be implemented. As opposed to extending classes, when you extend a class you are using some predefined code.

    If you extend two classes with the same method, say, methodA, and call this method, then, the compiler will not know which one will it need to run. On the other hand, when you implement two interfaces with the same method, since the implementation is written within your own code, the compiler will know where it needs to go to find the implementation.

    So basically, when you implement something you are guaranteeing you will be offering some service.

  • What is static class?
    In C#, one is allowed to create a static class, by using static keyword. A static class can only contain static data members, static methods, and a static constructor.It is not allowed to create objects of the static class. Static classes are sealed, means you cannot inherit a static class from another class.

    A static method has two main purposes: For utility or helper methods that don't require any object state. Since there is no need to access instance variables, having static methods eliminates the need for the caller to instantiate the object just to call the method.

    The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created. Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object.

    Only one instance of the object is created for static classes irrespective of how many calls are made to that static class

    What is Singleton pattern?
    Singleton is a design pattern that makes sure that your application creates only one instance of the class anytime. It is highly efficient and very graceful. Singletons have a static property that you must access to get the object reference. So you are not instantiating an object such as in the manner we do for a normal class.

    Purpose of both looks similar but there are some diffrences:

    • Singleton is an object creational pattern with one instance of the class.
    • Singleton can implement interfaces, inherits from other classes and it aligns with the OOPS concepts.
    • Singleton Object can be passed as a reference.
    • Singleton suports object disposal
    • Singleton object is stored on heap
    • Singleton object can be cloned.
  • Method Hiding :
    C# provides a concept to hide the methods of the base class from derived class, this concept is known as Method Hiding. It is also known as Method Shadowing.

    In method hiding, you can hide the implementation of the methods of a base class from the derived class using the new keyword. Or in other words, in method hiding, you can redefine the method of the base class in the derived class by using the new keyword.

        // method In base class
        public void member()
        {
             Console.WriteLine("Total number of family members: 3");
        }
        
        // Method In derived class
                                                              
        // Reimplement the method of the base class Using new keyword
        // It hides the method of the base class
        
        public new void member()
        {
             Console.WriteLine("Name: Rakesh, Age: 40 \nName: Somya, "+"Age: 39 \nName: Rohan, Age: 20 ");
        }
                                                            

    How to call a hidden method?
    In method hiding, you can also call the hidden method of the base class in the derived class using three different ways and the ways are:

    By using the base keyword you can call the hidden method of the base class in your derived class

        // In derived class
        public new void member() 
        {
            // Calling the hidden method of the base class in a derived class
            // Using base keyword
    
            base.member();
            Console.WriteLine("Name: Rakesh, Age: 40 \nName: Somya,"+" Age: 39 \nName: Rohan, Age: 20");
        }
                                                            

    By casting the derived class type to base class type you can invoke the hidden method. As shown in the below example. We know that in inheritance the derived class has all the capabilities of the base class so we can easily cast the object of a derived class into base class type.

        // Creating the object of the derived class
        My_Member obj = new My_Member();
      
        // Invoking the hidden method
        // By type casting
        ((My_Family)obj).member();
                                                            

    Method Overriding :
    Method Overriding is a technique that allows the invoking of functions from another class (base class) in the derived class.
    Creating a method in the derived class with the same signature as a method in the base class is called as method overriding.

    In simple words, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class. Method overriding is one of the ways by which C# achieve Run Time Polymorphism(Dynamic Polymorphism).

    In C# we can use 3 types of keywords for Method Overriding:
    virtual keyword: This modifier or keyword use within base class method. It is used to modify a method in base class for overridden that particular method in the derived class.
    override: This modifier or keyword use with derived class method. It is used to modify a virtual or abstract method into derived class which presents in base class.
    base Keyword: This is used to access members of the base class from derived class. It basically used to access constructors and methods or functions of the base class. The base keyword cannot use within a static method. Base keyword specifies which constructor of the base class should be invoked while creating the instances of the derived class.

    Use of Base keyword:
    1. Call methods or functions of base class from derived class.
    2. Call constructor internally of base class at the time of inheritance.

    Note:
    1. Method overriding is possible only in derived classes. Because a method is overridden in the derived class from the base class.
    2. A non-virtual or a static method can’t be overridden.
    3. Both the override method and the virtual method must have the same access level modifier.

    Method Overloading :
    Method Overloading is the common way of implementing polymorphism. It is the ability to redefine a function in more than one form. A user can implement function overloading by defining two or more functions in a class sharing the same name. C# can distinguish the methods with different method signatures. i.e. the methods can have the same name but with different parameters list (i.e. the number of the parameters, order of the parameters, and data types of the parameters) within the same class.It is also known as early binding or comple time polymorphism.

    • Overloaded methods are differentiated based on the number and type of the parameters passed as arguments to the methods.
    • You can not define more than one method with the same name, Order and the type of the arguments. It would be compiler error.
    • The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return type. It will throw a compile-time error. If both methods have the same parameter types, but different return type, then it is not possible.

    Why do we need Method Overloading ?
    If we need to do the same kind of the operation in different ways i.e. for different inputs. In the example described below, we are doing the addition operation for different inputs. It is hard to find many different meaningful names for single action.

  • SOLID design principles in C# are basic design principles one should know while doing OOP (Object Oriented Programming).
    The intention of these principles is to make software designs more understandable, easier to maintain and easier to extend.

    SOLID stands for:

    • Single Responsibility Principle (SRP)
    • Open Close Principle (OCP)
    • Liskov Substituion Principle (LSP)
    • Interface Segregation Principle (ISP)
    • Dependency Inversion Principle (DIP)

    Why is it required?
    The following are the design flaws that cause damage in software, mostly.

    • Putting more stress on classes by assigning more responsibilities to them. (A lot of functionality not related to a class.)
    • Forcing the classes to depend on each other. If classes are dependent on each other (in other words tightly coupled), then a change in one will affect the other.
    • Spreading duplicate code in the system/application.

    Solution

    • Choosing the correct architecture (in other words MVC, 3-tier, Layered, MVP, MVVP and so on).
    • Following Design Principles.
    • Choosing correct Design Patterns to build the software based on its specifications.

    Intro to SOLID principles
    SOLID principles are the design principles that enable us to manage most of the software design problems. Robert C. Martin compiled these principles in the 1990s. These principles provide us with ways to move from tightly coupled code and little encapsulation to the desired results of loosely coupled and encapsulated real needs of a business properly.

    1. Single Responsibility Principle (SRP) :
    => A class should take care of a single responsibility.
    => Every Software module should have only one reason to change.
    => A good separation of responsibilities is done only when we have the full picture of how the application should work.

    2. Open Close Principle (OCP) :
    => A software module/class is open for extension and close for modification.
    => It says prefere extension over modification.
    => Here "Open for extension" means, we need to design our module/class in such a way that the new functionality can be added only when new requirements are generated. "Closed for modification" means we have already developed a class and it has gone through unit testing. We should then not alter it until we find bugs. As it says, a class should be open for extensions, we can use inheritance to do this (Abstract Class).

    3. Liskov Substituion Principle (LSP) :
    => You should be able to use any derived class instead of a parent class and have it behave in the same manner without modification.
    => It ensures that a derived class does not affect the behavior of the parent class.
    => A derived class must be substitutable for its base class.
    => The parent class should be able to refer child objects seamlessly during runtime polymorphism

    4. Interface Segregation Principle (ISP) :
    => A client should not be forced to use and interface, If it does not need it or dont use.
    => Instead of one fat interface many small interfaces are prefered based on group of methods, each one serving one module.
    => An interface should be more closely related to the code that uses it than code that implements it. So the methods on the interface are defined by which methods the client code needs rather than which methods the class implements. So clients should not be forced to depend upon interfaces that they don't use.

    5. Dependency Inversion Principle (DIP) :
    => Higher level modules/classes should not be dependent on low level modules/classes, but should depend on abstraction.
    => A high-level module/class that has a dependency on low-level modules/classes or some other class and knows a lot about the other classes it interacts with is said to be tightly coupled. When a class knows explicitly about the design and implementation of another class, it raises the risk that changes to one class will break the other class. So we must keep these high-level and low-level modules/classes loosely coupled as much as we can. To do that, we need to make both of them dependent on abstractions instead of knowing each other

  • NET supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. Dependency injection in . NET is a first-class citizen, along with configuration, logging, and the options pattern.

    It allows the creation of dependent objects outside of a class and provides those objects to a class through different ways. Using DI, we move the creation and binding of the dependent objects outside of the class that depends on them.

    How does DI works in c#?
    Dependency Injection (DI) is a software design pattern. It allows us to develop loosely-coupled code.The intent of Dependency Injection is to make code maintainable. Dependency Injection helps to reduce the tight coupling among software components. Dependency Injection reduces the hard-coded dependencies among your classes by injecting those dependencies at run time instead of design time technically.

    We have the following 3 ways to implement Dependency Injection.

    • Constructor Injection in C#
    • Property Injection in C#
    • Method Injection in C#

    Constructor Injection in C#
    Construction injection is the most commonly used dependency pattern in Object Oriented Programming. The constructor injection normally has only one parameterized constructor, so in this constructor dependency there is no default constructor and we need to pass the specified value at the time of object creation.

    Property Injection in C#
    We use constructor injection, but there are some cases where I need a parameter-less constructor so we need to use property injection.

    Method Injection in C#
    In method injection we need to pass the dependency in the method only. The entire class does not need the dependency, just the one method.

  • The answer is no because static method does not need any object to be called, and this keyword always point to a current object of a class. simply if there is no object then how the keyword point to any current object so,we cannot use this keyword here.

    Because this points to an instance of the class, in the static method you don't have an instance.
    The this keyword refers to the current instance of the class. Static member functions do not have a this pointer.

  • An immutable object is defined as an object that cannot be changed after it has been created. For many use cases, such as Data Transfer Objects, immutability is a desirable feature.

    String objects are immutable: they cannot be changed after they have been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new string object.

    Strings are immutable, which means we are creating new memory everytime instead of working on existing memory.

  • Basically, a class combines the fields and methods(member function which defines actions) into a single unit. A structure is a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types.

    Difference between Structs and Classes:

    • Structs are value type whereas Classes are reference type.
    • Structs are stored on the stack whereas Classes are stored on the heap
    • A Class is instantiated using new keyword whereas Structs can be instantiated without using a new operator.
    • A Struct cannot inherit from another struct or class, and it cannot be the base of a class.
    • A class can inherit from another class, and it can be the base of a class.
    • When you copy struct into another struct, a new copy of that struct gets created modified of one struct won't affect the value of the other struct.
    • Class is generally used in large programs.Struct are used in small programs.
        // Defining structure
        public struct Car
        {
      
            // Declaring different data types
            public string Brand;
            public string Model;
            public string Color;
        }
        // no need to create an 
        // instance using 'new' keyword
        Car c1;
      
        // c1's data
        c1.Brand = "Bugatti";
        c1.Model = "Bugatti Veyron EB 16.4";
        c1.Color = "Gray";
                                                        
  • Both are used to define the architecture of the application.

    The short answer: An abstract class allows you to create functionality that subclasses can implement or override.
    An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.

    An abstract class can provide a complete implementation. The interface is comparatively slow. An abstract class is fast. The interface is absolutely abstract and cannot be instantiated.

    Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).

    Abstract class :
    An abstract class is a way to achieve the abstraction in C#. An Abstract class is never intended to be instantiated directly. This class must contain at least one abstract method, which is marked by the keyword or modifier abstract in the class definition. The Abstract classes are typically used to define a base class in the class hierarchy.

        abstract class Shape
        {
            public abstract int GetArea();
        }
    
        class Square : Shape
        {
            int side;
    
            public Square(int n) => side = n;
    
            // GetArea method is required to avoid a compile-time error.
            public override int GetArea() => side * side;
    
            static void Main() 
            {
                var sq = new Square(12);
                Console.WriteLine($"Area of the square = {sq.GetArea()}");
            }
        }
        // Output: Area of the square = 144
                                                        
    • The methods can have an implementation (be defined)
    • It's elements are private by default
    • It can contain fields
    • It can inherit from another abstract class or interface
    • It can have abstract and non-abstract methods.
    • The abstract classes have to be implemented in the child class.

    Interface : Interface in C# is a blueprint of a class. It is like abstract class because all the methods which are declared inside the interface are abstract methods. It cannot have method body and cannot be instantiated. It is used to achieve multiple inheritance which can't be achieved by class.

    • It's not a class, it's an entity
    • The methods can't have an implementation
    • It's elements are public by default and can't have access modifiers
    • It can't contain fields like for example, "private int count", but it can contain properties
    • It can only inherit from another interface
    • A class can inherit from multiple interfaces
    • A class inheriting from an interface, has to implement all it's methods

    Table Of diffrence :

    The Basis of comparison 

    C# Interface

    C# Abstract Class

    Access Specifier In C#, Interface cannot have an access specifier for functions. It is public by default. In C#, an abstract class can have access to a specifier for functions.
    Implementation In C#, an interface can only have a signature, not the implementation. An abstract class can provide a complete implementation.
    Speed The interface is comparatively slow. An abstract class is fast.
    Instantiate The interface is absolutely abstract and cannot be instantiated. An abstract class cannot be instantiated.
    Fields The interface cannot have fields. An abstract class can have defined fields and constants.
    Methods The interface has only abstract methods. An abstract class can have non-abstract methods.
  • Is it possible to override private virtual methods? no,you can not override the private virtual method bcoz virtual method cannot be private!!! CLR doesn't allow to write private virtual method, so its not possible at all.

    Virtual Methods are declared as :

        abstract class Shape
        {
    	     public double distance=0.0;  
    	     public double hour =0.0;  
    	     public double fuel =0.0;   	
    	 
    	     // abstrcat method, 
    	     // It cant have implementation
            public abstract int GetArea();
    	
    	    //Virtual method
    	    public virtual void Speed()  
            {  
                   double speed = 0.0;  
                   speed = distance / hour;  
                   Console.WriteLine("Vehicle Speed is {0:0.00}", speed);  
            } 
        }
    
        class Square : Shape
        {
            int side;
    
            public Square(int n) => side = n;
    
            // GetArea method is required to avoid a compile-time error.
            public override int GetArea() => side * side;
    	
    	     public override void Speed()  
             {  
                    double speed = 0.0;             
                    speed = distance / hour;  
                    Console.WriteLine("Car Speed is {0:0.00}", speed);  
             }  
    
            static void Main() 
            {
                var sq = new Square(12);
                Console.WriteLine($"Area of the square = {sq.GetArea()}");
            }
        }
                                                        
  • A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime. Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.

    Points To remember :

    • Delegates allow methods to be passed as parameters.
    • Delegates are type safe function pointer.
    • Delegate instances attach or detach a method at run time making it more dynamic and flexible to use.
    • Delegates can invoke more than one method using the Multicast feature.
    • Delegates are of reference types.

    Simple deligate :

        public delegate void MyDeligate(string var);  
        protected void Page_Load(object sender, EventArgs e)  
      
        {  
            if (!IsPostBack)  
            {  
                MyDeligate obj_deligate = new MyDeligate(GetData);  
                obj_deligate("Mahesh");  
            }  
        }  
        public void GetData(string Name)  
        {  
            lblName.Text = Name;  
        } 
                                                        

    Multicast Delegate:
    It is a delegate that holds the reference of more than one method.
    Multicast delegates must contain only methods that return void, else there is a run-time exception.

        public delegate void MyDeligate(string var);  
        protected void Page_Load(object sender, EventArgs e)  
        {  
      
            if (!IsPostBack)  
            {  
                MyDeligate objMyDeligate = new MyDeligate(GetData);  
                objMyDeligate += new MyDeligate(GetDat_one);  
                //GetData and GetDat_one is called  
                objMyDeligate("Pradeeep");  
                objMyDeligate -= new MyDeligate(GetDat_one);  
                lblName.Text = lblName.Text + "
    "; //GetData is called objMyDeligate("Manish"); } } public void GetData(string Name){ lblName.Text = lblName.Text + "GetData : " + Name; } public void GetData_B(string Name) { lblName.Text = lblName.Text + " GetData_B : " + Name; }

    Another example

    myDelegate d1 = new myDelegate(Method1);
    myDelegate d2 = new myDelegate(Method2);
    myDelegate multicastDelegate = (myDelegate)Delegate.Combine(d1, d2);
    multicastDelegate.Invoke();

  • Design Pattern provides a general solution or a flexible way to solve a common design problem.

    Design Patterns in the object-oriented world is a reusable solution to common software design problems that occur repeatedly in real-world application development. It is a template or description of how to solve problems that can be used in many situations. "A pattern is a recurring solution to a problem in a context".

    Design patterns can be broadly categorized in 3 categories : Creational, Structural and Behavioral

    Creational Pattern :

    • Abstract Factory : Creates an instance of several families of classes
    • Builder : Separates object construction from its representation
    • Factory Method : Creates an instance of several derived classes
    • Prototype : A fully initialized instance to be copied or cloned
    • Singleton : A class of which only a single instance can exist.
      1. A private static variable, holding the only instance of the class.
      2. A private constructor, so it cannot be instantiated anywhere else.
      3. A public static method, to return the single instance of the class.

    Structural Pattern :

    • Adapter : Match interfaces of different classes
    • Bridge : Separates an object’s interface from its implementation
    • Composite : A tree structure of simple and composite objects
    • Decorator : Add responsibilities to objects dynamically
    • Facade : A single class that represents an entire subsystem
    • Flyweight : A fine-grained instance used for efficient sharing
    • Proxy : An object representing another object

    Behavioral Patterns :

    • Chain of Resp. : A way of passing a request between a chain of objects
    • Command : Encapsulate a command request as an object
    • Interpreter : A way to include language elements in a program
    • Iterator : Sequentially access the elements of a collection
    • Mediator : Defines simplified communication between classes
    • Observer : A way of notifying change to a number of classes
    • State : Alter an object's behavior when its state changes
    • Strategy : Encapsulates an algorithm inside a class
    • Template Method : Defer the exact steps of an algorithm to a subclass
    • Visitor : Defines a new operation to a class without change
  • The Common Language Runtime (CLR) manages allocation and deallocation of a managed object in memory. C# programmers never do this directly, there is no delete keyword in the C# language. It relies on the garbage collector. The . NET objects are allocated to a region of memory termed the managed heap.

    In C# Reference types (classes, interfaces, delegates) are always allocated on the heap.

    Value types (derived from System.ValueType, e.g. int, bool, char, enum and any struct) can be allocated on the heap or on the stack, depending on where they were declared

    Now, in the above example, line one is executed then it is stored in Stack. The same process goes for line 2, however, when 3rd line is executed, its reference will be stored on the stack, i.e., class1 obj and its values will be stored on the heap. Once the execution of Method1() gets completed, all memory from stack gets cleared, however, values present in heap will remain there, i.e., obj of class1.
    Now, the values present in heap may be cleared by Garbage collector.
    However, we can say normal variables like int, Boolean, double float are stored on stack and objects are stored on Heap.

    Who goes where ?

    • If the value type was declared as a variable inside a method then it's stored on the stack.
    • If the value type was declared as a method parameter then it's stored on the stack.
    • If the value type was declared as a member of a class then it's stored on the heap, along with its parent.
    • If the value type was declared as a member of a struct then it's stored wherever that struct is stored.
  • The CLR stands for Common Language Runtime and it is an Execution Environment (virtual machine component of Microsoft . NET Framework). It works as a layer between Operating Systems and the applications written in . NET languages that conform to the Common Language Specification (CLS)

    CLR is the basic and Virtual Machine component of the .NET Framework. It is the run-time enviornment in the .NET Framework that runs the codes and helps in making the development process easier by providing the various services. Basically, it is responsible for managing the execution of .NET programs regardless of any .NET programming language.

    Common Language Runtime (CLR) manages the execution of . NET programs. The just-in-time compiler converts the compiled code into machine instructions. This is what the computer executes. The services provided by CLR include memory management, exception handling, type safety, etc.

    • Suppose you have written a C# program and save it in a file which is known as the Source Code.
    • Language specific compiler compiles the source code into the MSIL(Microsoft Intermediate Language) which is also know as the CIL(Common Intermediate Language) or IL(Intermediate Language) along with its metadata. Metadata includes the all the types, actual implementation of each function of the program. MSIL is machine independent code.
    • Now CLR comes into existence. CLR provides the services and runtime environment to the MSIL code. Internally CLR includes the JIT(Just-In-Time) compiler which converts the MSIL code to machine code which further executed by CPU. CLR also uses the .NET Framework class libraries. Metadata provides information about the programming language, environment, version, and class libraries to the CLR by which CLR handles the MSIL code. As CLR is common so it allows an instance of a class that written in a different language to call a method of the class which written in another language.

    Main Components of CLR are :

    • Common Language Specification (CLS) : Handles Manage Vs Unmanaged codes
    • Common Type System (CTS) : handles value type and reference type
    • Garbage Collector (GC): It is used to provide the Automatic Memory Management feature. If there was no garbage collector, programmers would have to write the memory management codes which will be a kind of overhead on programmers.
    • Just In Time Compiler (JIT): t is responsible for converting the CIL(Common Intermediate Language) into machine code or native code using the Common Language Runtime environment.
  • Reflection concept in C# is ability of inspecting metadata of an assembly at runtime. In other words, an assembly content is described by looking at the assembly metadata at runtime by loading a library in memory and reading its attributes.

    Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies, modules and type information at runtime. The classes that give access to the metadata of a running program are in System.Reflection.

    System.Reflection namespace defines the following types to analyze the module's metadata of an assembly: Assembly, Module, Enum, ParameterInfo, MemberInfo, Type, MethodInfo, ConstructorInfo, FieldInfo, EventInfo, and PropertyInfo.

    Assembly Metadata :
    An assembly is a logical DLL or EXE, which is described by manifest, the detailed description (metadata) of an assembly. The .NET compiler produces a portable executable PE file for CLR with the extensions of .exe or .dll. This PE file is mainly comprised of metadata and IL (Intermediate Language).
    By using refection, an assembly can be inspected.

        Type _type = Type.GetType("ReflectionConcept.Employee");  
        Or  
        Type _type = typeof(Employee);  
        
        class Program  
        {  
            static void Main(string[] args)  
            {  
               Type _type = Type.GetType("ReflectionConcept.Employee");  // namespace.classname
      
               // Type _type = typeof(Employee);  
      
      
                Console.WriteLine(_type.FullName);  
                Console.WriteLine(_type.Namespace);  
                Console.WriteLine(_type.Name);  
      
                PropertyInfo[] info  = _type.GetProperties();  
      
                foreach (PropertyInfo propinfo in info)  
                {  
                    Console.WriteLine(propinfo.Name);  
                }  
      
                MethodInfo [] methods=_type.GetMethods();  
      
                foreach (MethodInfo methodinfo in methods)  
                {  
                    Console.WriteLine(methodinfo.ReturnType.Name);  
                    Console.WriteLine(methodinfo.Name);  
                }  
      
                Console.ReadLine();  
            }          
        }  
    } 
                                                        

    Uses of Reflections:
    Refection is heavily used by develoepr IDEs or UI designers such as Visual Studio. The Property window of a .NET application uses refection to show list of properties.

    Important Sticky

    • It allows view attribute information at runtime.
    • It allows examining various types in an assembly and instantiate these types.
    • It allows late binding to methods and properties
    • It allows creating new types at runtime and then performs some tasks using those types.
  • Try...Catch block can be defined without finally or Catch. But Try statement must be defined with either Catch or finally block. Without both Try block cannot be executed independently. More over it must be useless.

  • In C#, You can use more than one catch block with the try block. ... If you use multiple catch blocks for the same type of exception, then it will give you a compile-time error because C# does not allow you to use multiple catch block for the same type of exception.

    when one catch block is executed, controls skip all other catch blocks and goes to finally block. No, Multiple catch blocks can't be executed. Once the proper catch code executed, the control is transferred to the finally block and then the code that follows the finally block gets executed.

                                                            // --------- try block ---------
      
        for (int j = 0; j < number.Length; j++)
        {
            // Here this block raises two different
            // types of exception, i.e. DivideByZeroException
            // and IndexOutOfRangeException
            try {
      
                Console.WriteLine("Number: " + number[j]);
                Console.WriteLine("Divisor: " + divisor[j]);
                Console.WriteLine("Quotient: " + number[j] / divisor[j]);
            }
      
            // Catch block 1
      
            // This Catch block is for
            // handling DivideByZeroException
            catch (DivideByZeroException) {
      
                Console.WriteLine("Not possible to Divide by zero");
            }
      
            // Catch block 2
      
            // This Catch block is for
            // handling IndexOutOfRangeException
            catch (IndexOutOfRangeException) {
                Console.WriteLine("Index is Out of Range");
            }
        }
                                                        
  • In C#, an anonymous type is a type (class) without any name that can contain public read-only properties only. It cannot contain other members, such as fields, methods, events, etc.

    You create an anonymous type using the new operator with an object initializer syntax. The implicitly typed variable- var is used to hold the reference of anonymous types.

        var student = new { Id = 1, FirstName = "James", LastName = "Bond" };
                                                        

    The properties of anonymous types are read-only and cannot be initialized with a null, anonymous function, or a pointer type. The properties can be accessed using dot (.) notation, same as object properties. However, you cannot change the values of properties as they are read-only.

        var student = new { Id = 1, FirstName = "James", LastName = "Bond" };
        Console.WriteLine(student.Id); //output: 1
        Console.WriteLine(student.FirstName); //output: James
        Console.WriteLine(student.LastName); //output: Bond
    
        student.Id = 2;//Error: cannot chage value
        student.FirstName = "Steve";//Error: cannot chage value
        // nested Anonymous Types example
        var student = new { 
            Id = 1, 
            FirstName = "James", 
            LastName = "Bond",
            Address = new { Id = 1, City = "London", Country = "UK" }
        };
        // Array of Anonymous Types
        var students = new[] {
                new { Id = 1, FirstName = "James", LastName = "Bond" },
                new { Id = 2, FirstName = "Steve", LastName = "Jobs" },
                new { Id = 3, FirstName = "Bill", LastName = "Gates" }
        };                                           
    
                                                        

    An anonymous type will always be local to the method where it is defined. It cannot be returned from the method. However, an anonymous type can be passed to the method as object type parameter, but it is not recommended. If you need to pass it to another method, then use struct or class instead of an anonymous type.

  • Type casting is when you assign a value of one data type to another type.
    In C#, there are two types of casting:
    1.Implicit Casting (automatically) - converting a smaller type to a larger type size
    char -> int -> long -> float -> double
    2.Explicit Casting (manually) - converting a larger type to a smaller size type
    double -> float -> long -> int -> char

    Implicit Casting :
    Implicit casting is done automatically when passing a smaller size type to a larger size type:

        int myInt = 9;
        double myDouble = myInt;       // Automatic casting: int to double
    
        Console.WriteLine(myInt);      // Outputs 9
        Console.WriteLine(myDouble);   // Outputs 9
                                                        

    Explicit Casting :
    Explicit casting must be done manually by placing the type in parentheses in front of the value:

        double myDouble = 9.78;
        int myInt = (int) myDouble;    // Manual casting: double to int
    
        Console.WriteLine(myDouble);   // Outputs 9.78
        Console.WriteLine(myInt);      // Outputs 9
                                                        

    Type Conversion Methods :
    It is also possible to convert data types explicitly by using built-in methods, such as Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (int) and Convert.ToInt64 (long):

        int myInt = 10;
        double myDouble = 5.25;
        bool myBool = true;
    
        Console.WriteLine(Convert.ToString(myInt));    // convert int to string
        Console.WriteLine(Convert.ToDouble(myInt));    // convert int to double
        Console.WriteLine(Convert.ToInt32(myDouble));  // convert double to int
        Console.WriteLine(Convert.ToString(myBool));   // convert bool to string
                                                        
  • C# does not support multiple inheritance , because they reasoned that adding multiple inheritance added too much complexity to C# while providing too little benefit. In C#, the classes are only allowed to inherit from a single parent class, which is called single inheritance .

    Multiple inheritance can lead to dimond problem.

    To overcome this problem we use interfaces to achieve multiple class inheritance.As interface contains only declaration of methods and his implementation is provided by classes that implements that interface.

  • HTTP response status codes indicate whether a specific HTTP request has been successfully completed.
    Responses are grouped in five classes:

    • Informational responses (100–199)
    • Successful responses (200–299)
    • Redirects (300–399)
    • Client errors (400–499)
    • Server errors (500–599)
    • 1. Information responses
    • a. 100 Continue
    • b. 101 Switching Protocol
    • c. 102 Processing (WebDAV)
    • d. 103 Early Hints
    • 2. Successful responses
    • a. 200 OK
    • b. 201 Created
    • c. 202 Accepted
    • d. 203 Non-Authoritative Information
    • e. 204 No Content
    • f. 205 Reset Content
    • g. 206 Partial Content
    • h. 207 Multi-Status (WebDAV)
    • i. 208 Already Reported (WebDAV)
    • j. 226 IM Used (HTTP Delta encoding)
    • 3. Redirection messages
    • a. 300 Multiple Choice
    • b. 301 Moved Permanently
    • c. 302 Found
    • d. 303 See Other
    • e. 304 Not Modified
    • f. 305 Use Proxy
    • g. 306 unused
    • h. 307 Temporary Redirect
    • i. 308 Permanent Redirect
    • 4. Client error responses
    • a. 400 Bad Request
    • b. 401 Unauthorized
    • c. 402 Payment Required
    • d. 403 Forbidden
    • e. 404 Not Found
    • f. 405 Method Not Allowed
    • g. 406 Not Acceptable
    • h. 407 Proxy Authentication Required
    • i. 408 Request Timeout
    • j. 409 Conflict
    • k. 410 Gone
    • l. 411 Length Required
    • m. 412 Precondition Failed
    • n. 413 Payload Too Large
    • o. 414 URI Too Long
    • p. 415 Unsupported Media Type
    • q. 416 Range Not Satisfiable
    • r. 417 Expectation Failed
    • s. 418 I'm a teapot
    • t. 421 Misdirected Request
    • u. 425 Too Early
    • v. 426 Upgrade Required
    • w. 428 Precondition Required
    • x. 429 Too Many Requests
    • y. 431 Request Header Fields Too Large
    • z. 451 Unavailable For Legal Reasons
    • 5. Server error responses
    • a. 500 Internal Server Error
    • b. 501 Not Implemented
    • c. 502 Bad Gateway
    • d. 503 Service Unavailable
    • e. 504 Gateway Timeout
    • f. 505 HTTP Version Not Supported
    • g. 506 Variant Also Negotiates
    • h. 507 Insufficient Storage (WebDAV)
    • i. 508 Loop Detected (WebDAV)
    • j. 510 Not Extended
    • k. 511 Network Authentication Required
  • The Equality Operator (==) is the comparison operator and the Equals() method in C# is used to compare the content of a string. The Equals() method compares only content.

    • == compares object references. it'll resolve to System.Object.ReferenceEquals.
    • Equals compares object content.
    • String datatypes always act like content comparison.
        string str = "hello";
        string str2 = str;
        Console.WriteLine("Using Equality operator: {0}", str == str2); // Print True
        Console.WriteLine("Using equals() method: {0}", str.Equals(str2));  // Print True
    
        object str = "hello";
        char[] values = {'h','e','l','l','o'};
        object str2 = new string(values);
        Console.WriteLine("Using Equality operator: {0}", str == str2);     // False
        Console.WriteLine("Using equals() method: {0}", str.Equals(str2));  // True
     
  • The most recent version is 9.0, which was released in 2020 in .NET 5.0 and included in Visual Studio 2019 version 16.8. Mono is a free and open-source project to develop a cross-platform compiler and runtime environment (i.e. virtual machine) for the language.

    Some of C# 7.0 new features are :

    • Tuples and discards.
    • Pattern Matching.
    • async Main method.
    • Local Functions.
    • More expression-bodied members.
    • throw Expressions.
    • default literal expressions.
    • Numeric literal syntax improvements.
  • Serialization takes an in-memory data structure and converts it into a series of bytes that can be stored and transferred. Deserialization takes a series of bytes and converts it to an in-memory data structure that can be consumed programmatically.

    Serialisation is the process of translating a data structure or object state into a format that can be stored (for example, in a file or memory data buffer) or transmitted (for example, across a computer network) and reconstructed later (possibly in a different computer environment)

  • Abstraction :
    Abstraction is the process of hiding certain details and showing only essential information to the user.Eg. Like for the method Console.WriteLine(), no one knows what actually is happening behind the function calling. We are just using it by calling and passing the arguments. This is the thing called Abstraction.

    Encapsulation :
    Encapsulation is a process of wrapping the data and the code, that operate on the data into a single entity. You can assume it as a protective wrapper that stops random access of code defined outside that wrapper.

    Let's understand it with an example :

        class User
        {
            public bool AddUser(string name, string email, string phone)
            {
                if (ValidateUser(name, email, phone))
                {
                    if (AddtoDb(name, email, phone) > 0)
                    {
                        return true;
                    }
                }
                return false;
            }
    
            private bool ValidateUser(string name, string email, string phone)
            {
                // do your validation
                return true;
            }
    
            private int AddtoDb(string name, string email, string phone)
            {
                // Write the Db code to insert the data
                return 1;
            }
        }
                                                        

    As you can see, there are three methods that are written in this User class.

    • AddUser: To call from outside the class. That is why the access modifier is public.
    • validateUser: To validate the user's details. Can't access from outside the class. It's private.
    • AddtoDb: To insert data into database table and again it is private, can't access from outside the class.

    Now another user will just call AddUser method with parameters. And that user has no idea what is actually happening inside the method.
    To call the AddUser method, do as follows:

        class Program
        {
            static void Main(string[] args)
            {
                User objUser = new User();
                bool f = objUser.AddUser("pradeep", "pradeep@gmail.com", "98000000000");
            }
        }
                                                         

    Conclusion
    Here, we are hiding the procedure of adding data into database from other users, this is Abstraction. And putting all the three methods into one User class and providing other users to use it, that is called Encapsulation.
    So procedure hiding is Abstraction and putting every necessary thing into one is Encapsulation.

  • A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed only onces. It is called automatically before the first instance is created or any static members are referenced.

    A static constructor does not allow any access modifier and only declare with static keyword followed by class name

  • Entity Framework is an open-source ORM framework for . NET applications supported by Microsoft. It enables developers to work with data using objects of domain specific classes without focusing on the underlying database tables and columns where this data is stored.

    Advantages of Entity Framework:

    • It provides auto generated code
    • It reduce development time
    • It reduce development cost
    • It enables developers to visually design models and mapping of database
    • It provides capability of programming a conceptual model.
    • It provides unique syntax (LINQ / Yoda) for all object queries whether it is database or not
    • It allow multiple conceptual models to mapped to a single storage schema
    • It’s easy to map business objects (with drag & drop tables).

    Disadvantages of Entity Framework:

    • Lazy loading is the main drawbacks of EF
    • Its syntax is complicated
    • Its logical schema is not able to understand business entities and relation among each other
    • Logical schema of database is not capable of using certain parts of application
    • It is not available for every RDMS
    • Need to handle data in nontraditional way
    • It does not work if we change any schema of the database. We need to update the schema on the solution.
    • It is not good for huge domain model.

    All in all we can say entity frameworks are good for small range of applications. But if we overcome the drawbacks of EF it will be perfect for any type of applications.

  • Code First Approach :
    In code first approach we will first create entity classes with properties defined in it. Entity framework will create the database and tables based on the entity classes defined. So database is generated from the code. When the dot net code will run database will get created.

    Advantages :

    • You can create the database and tables from your business objects.
    • You can specify which related collections are to be eager loaded, or not be serialized at all.
    • Database version control.
    • Good for small applications.

    Disadvantages :

    • You have to write everything related to database in the visual studio code.
    • For stored procedures you have to map stored procedure using Fluent API and write Stored Procedure inside the code.
    • If you want to change anything in the database tables you to make changes in the entity classes in the code file and run the update-database from the package manager console.
    • Not preferred for Data intensive applications.

    Database First Approach :
    In this approach Database and tables are created first. Then you create entity Data Model using the created database.

    Advantages :

    • Simple to create the data model
    • Graphical user interface.
    • Mapping and creation of keys and relationships are easy as you need not have to write any code .
    • Preferred for data intense and large applications

    Disadvantages :

    • Using an existing database to generate a .edmx model file and the associated code models results in a giant pile of auto generated code.
    • When you need to add any functionality to generated model you have to extend the model class generated.
  • The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

    Available in C# 8.0 and later, the null-coalescing assignment operator ??= assigns the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null. The ??= operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

        List<int> numbers = null;
        int? a = null;
    
        (numbers ??= new List<int>()).Add(5);
        Console.WriteLine(string.Join(" ", numbers));  // output: 5
    
        numbers.Add(a ??= 0);
        Console.WriteLine(string.Join(" ", numbers));  // output: 5 0
        Console.WriteLine(a);  // output: 0
                                                        

    The left-hand operand of the ??= operator must be a variable, a property, or an indexer element.

  • ADO.NET provides better performance as it is directly connected to the data source, which makes the processing faster than Entity Framework as it translates LINQ queries to SQL first then process the query.

  • An Anonymous method is a method without a name. Anonymous methods in C# can be defined using the delegate keyword and can be assigned to a variable of delegate type.

    It is useful when the user wants to create an inline method and also wants to pass parameter in the anonymous method like other methods. An Anonymous method is defined using the delegate keyword and the user can assign this method to a variable of the delegate type.

    Points To Remember :

    • Anonymous method can be defined using the delegate keyword
    • Anonymous method must be assigned to a delegate.
    • Anonymous method can access outer variables or functions.
    • Anonymous method can be passed as a parameter.
    • Anonymous method can be used as event handlers.
        public delegate void Print(int value);
    
        static void Main(string[] args)
        {
            Print print = delegate(int val) { 
                Console.WriteLine("Inside Anonymous method. Value: {0}", val); 
            };
    
            print(100);
        }
                                                        
  • Hashtable
    The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. It uses the key to access the elements in the collection. A hash table is used when you need to access elements by using key, and you can identify a useful key value.

        using System;
        using System.Collections;
    
        namespace CollectionsApplication {
           class Program {
              static void Main(string[] args) {
                 Hashtable ht = new Hashtable();
             
                 ht.Add("001", "Zara Ali");
                 ht.Add("002", "Abida Rehman");
                 ht.Add("003", "Joe Holzner");
                 ht.Add("004", "Mausam Benazir Nur");
                 ht.Add("005", "M. Amlan");
                 ht.Add("006", "M. Arif");
                 ht.Add("007", "Ritesh Saikia");
             
                 if (ht.ContainsValue("Nuha Ali")) {
                    Console.WriteLine("This student name is already in the list");
                 } else {
                    ht.Add("008", "Nuha Ali");
                 }
             
                 // Get a collection of the keys.
                 ICollection key = ht.Keys;
             
                 foreach (string k in key) {
                    Console.WriteLine(k + ": " + ht[k]);
                 }
                 Console.ReadKey();
              }
           }
        }
                                                        

    Dictionary
    In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.Collection.Generic namespace. It is dynamic in nature means the size of the dictionary is grows according to the need.

        // Creating a dictionary using Dictionary<TKey,TValue> class
    	Dictionary<int, string> My_dict1 =  new Dictionary<int, string>(); 
    
    	// Adding key/value pairs in the Dictionary Using Add() method
    
    	My_dict1.Add(1123, "Welcome");
    	My_dict1.Add(1124, "to");
    	My_dict1.Add(1125, "GeeksforGeeks");
    
    	foreach(KeyValuePair<int, string> ele1 in My_dict1)
    	{
    	  Console.WriteLine("{0} and {1}",ele1.Key, ele1.Value);
    	}
    	Console.WriteLine();
        
        // Other Ways are :
         var cities = new Dictionary<string, string>(){
    	{"UK", "London, Manchester, Birmingham"},
    	{"USA", "Chicago, New York, Washington"},
    	{"India", "Mumbai, New Delhi, Pune"}
        };
        
        // Other Ways are :
        var students2 = new Dictionary<int, StudentName>()
        {
            [111] = new StudentName { FirstName="Sachin", LastName="Karnik", ID=211 },
            [112] = new StudentName { FirstName="Dina", LastName="Salimzianova", ID=317 } ,
            [113] = new StudentName { FirstName="Andy", LastName="Ruth", ID=198 }
        };                                                     
    
                                                        
  • UpdatePanel controls are a central part of AJAX functionality in ASP.NET. They are used with the ScriptManager control to enable partial-page rendering. Partial-page rendering reduces the need for synchronous postbacks and complete page updates when only part of the page has to be updated.

    The ScriptManager control is central to Ajax functionality in ASP.NET. The control manages all ASP.NET Ajax resources on a page. This includes downloading Microsoft Ajax Library scripts to the browser and coordinating partial-page updates that are enabled by using UpdatePanel controls.

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

Frequently Asked ASP.NET AJAX Questions

  • AJAX = Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

    AJAX uses both a browser built-in XMLHttpRequest object to get data from the web server and JavaScript and HTML DOM to display that content to the user. Despite the name “AJAX” these calls can also transport data as plain text or JSON instead of XML. AJAX calls use a JavaScript snippet to load dynamic content.

    Usages :

    • Ajax allows you to make asynchronous calls to a web server.
    • The main purpose of Ajax is to improve the speed, performance and usability of a web application.
    • AJAX is a technique for creating fast and dynamic web pages.
    • Reduced server hits and network load.
    • Faster page renders and improved response times.
  • AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

    • An event occurs in a web page (the page is loaded, a button is clicked)
    • An XMLHttpRequest object is created by JavaScript.
    • The XMLHttpRequest object sends a request to a web server.
    • The server processes the request.
    • The server sends a response back to the web page.
    • The response is read by JavaScript.
    • Proper action (like page update) is performed by JavaScript

    AJAX Syntax :

       showload();
    	$.ajax({
            type: "POST",
            url: prefixurl + 'Index.aspx/get_grid_data',
            data: JSON.stringify({
                type: ""
            }),
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            async: true,
            success: function (data) {
               
                    var objdata = $.parseJSON(data.d);
                    var obj = objdata;
    				
    				alert((objdata["Table"][0]["MSG"] != null ? objdata["Table"][0]["MSG"] : ""))
    				
    				// Bind some grid based on json
    				
    				hideload();
            }//  success: function (data) {
        });// $.ajax({
                                                        
  • By default async is true. it means process will be continuing in jQuery ajax without wait of request.
    Async false means it will not go to next step untill the response will come.

    async:false = Code paused. (Other code waiting for this to finish.)
    async:true = Code continued. (Nothing gets paused. Other code is not waiting.)

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

Frequently Asked Web Technology Questions

  • A content delivery network, commonly referred to as CDN, is a network of edge servers strategically placed across the globe with the purpose of delivering digital content to users as fast as possible. When a user makes a request it is routed to the nearest CDN edge server, which significantly reduces the latency. A CDN allows all users, no matter the geographical location, to have fast loading content for an unquestionably improved experience.

    A content delivery network or content distribution network (CDN) is a globally distributed network of proxy servers deployed in multiple data centers.

    How does a CDN work?
    As mentioned, a CDN is a large network made up of various servers located in multiple geographic regions. The POPs are placed close to populated areas, in countries all over the world. For large countries, there may be many different POPs.
    The idea is to direct the user to the closest point of presence. When a user requests content from a site that uses a CDN, the request is routed to the closest POP, where a web server sends the requested data. There are several different ways that a request can be routed to a specific POP, one of which is IP anycast.

    In specific terms, CDN technology should provide the following primary benefits to a business:

    • Performance
    • Availability
    • Security
    • Intelligence
  • Web application performance optimization involves monitoring and analyzing app performance and pinpointing the ways you can improve it

    • Take Advantage of Key Metrics
    • Employ a Content Delivery Network (CDN) to Reduce Latency
    • Be Thoughtful in Your Caching
    • Bundle Your Files
    • Optimize Your Images
    • Keep Your Web Server Up to Date
    • Reduce Your Number of HTTP Requests
    • Use Logs to Monitor Performance
    • Choose the Right Tools for Web App Performance Optimization
  • App performance metrics are specific to the speed of the web applications that are running. If you’re having issues with an application performing slowly, these metrics are a good place to start.

    • Metric 1: Requests per second.
    • Metric 2: Data in and data out.
    • Metric 3: Average response time.
    • Metric 4: Peak response time.
    • Metric 5: Hardware utilization.
    • Metric 6: Thread count.
    • Metric 7: Uptime.
    • Metric 8: HTTP server error rate.
  • The Agile methodology is a way to manage a project by breaking it up into several phases. It involves constant collaboration with stakeholders and continuous improvement at every stage. Once the work begins, teams cycle through a process of planning, executing, and evaluating.

    agile practices involve discovering requirements and developing solutions through the collaborative effort of self-organizing and cross-functional teams and their customer/end user.

    Benifits :
    By breaking down the project into manageable units, the project team can focus on high-quality development, testing.

    • More Control
    • Better Productivity
    • Better Quality
    • Higher Customer Satisfaction
    • Higher Return on Investment
  • SOAP (Simple Object Access Protocol) is a communication protocol designed to communicate via Internet. SOAP can extend HTTP for XML messaging. SOAP provides data transport for Web services. SOAP can exchange complete documents or call a remote procedure. SOAP can be used for broadcasting a message.

    SOAP is an XML-based protocol for accessing web services over HTTP. It has some specification which could be used across all applications. ... SOAP is a protocol or in other words is a definition of how web services talk to each other or talk to client applications that invoke them.

    • It has strict rule on how to send request and response.
    • Soap Request use XML format to send and receive response
    • Only method allowed in SOAP is POST
    • The content type is always xml
    • Body is enclosed in envelop like structure for example

    Sample Post request to turn number into word
    POST https://www.dataaccess.com/webservicesserver/NumberConversion.wso

        Header : text/xml; charset=utf-8
    
        Body :
    
        <?xml version="1.0" encoding="utf-8"?>
        <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
          <soap:Body>
            <NumberToWords xmlns="http://www.dataaccess.com/webservicesserver/">
              <ubiNum>123456789</ubiNum>
            </NumberToWords>
          </soap:Body>
        </soap:Envelope>
        Response
    
        <?xml version="1.0" encoding="utf-8"?>
        <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
            <soap:Body>
                <m:NumberToWordsResponse xmlns:m="http://www.dataaccess.com/webservicesserver/">
                    <m:NumberToWordsResult>one hundred and twenty three million four hundred and fifty six thousand seven hundred and eighty nine </m:NumberToWordsResult>
                </m:NumberToWordsResponse>
            </soap:Body>
        </soap:Envelope>
                                                        
  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here

  • Sample answer here