Search This Blog

Q81-Q85

Q81. Can I create object of any type in Using block in C# i.e Can I create object not related to unmanaged resource in using block?
Q82. Write syntax of simple Abstract Class?
Q83. What is inheritance?
Q84. Can we inherit constructor of a base class?
Q85. What are the difference between HttpHandler and Http Module?

=======================================================================
Q81. Can I create object of any type in Using block in C# i.e Can I create object not related to unmanaged resource in using block?

Answer:
 No. We will get error and we have to implement IDisposable interface to make it workable. 

It's saying that "type used in using statement must be implicitly convertible to System.IDisposable". That means, please Implement the IDisposable Interface to keep the class object within the using block. 
But if we have implemented any class like fileread, or reading from DB we might not have seen this error because in those case IDisposable interface is implemented internally  by C#.
=======================================================================
Q82. Write syntax of simple Abstract Class?

Answer:
// C# program to show the
// working of abstract class
using System;

// abstract class 'GeeksForGeeks'
public abstract class GeeksForGeeks {

// abstract method 'gfg()'
public abstract void gfg();
}

// class 'GeeksForGeeks' inherit
// in child class 'Geek1'
public class Geek1 : GeeksForGeeks
{

// abstract method 'gfg()'
// declare here with
// 'override' keyword
public override void gfg()
{
Console.WriteLine("class Geek1");
}
}

// class 'GeeksForGeeks' inherit in
// another child class 'Geek2'
public class Geek2 : GeeksForGeeks
{

// same as the previous class
public override void gfg()
{
Console.WriteLine("class Geek2");
}
}

// Driver Class
public class main_method {

// Main Method
public static void Main()
{

// 'g' is object of class
// 'GeeksForGeeks' class '
// GeeksForGeeks' cannot
// be instantiate
GeeksForGeeks g;

// instantiate class 'Geek1'
g = new Geek1();
// call 'gfg()' of class 'Geek1'
g.gfg();
// instantiate class 'Geek2'
g = new Geek2();
// call 'gfg()' of class 'Geek2'
g.gfg();
}
}

=============================================================================
Q83. What is inheritance?

Answer:
Inheritance is a concept in which you define parent classes and child classes. The child classes inherit methods and properties of the parent class, but at the same time, they can also modify the behavior of the methods if required.
=============================================================================
Q84. Can we inherit constructor of a base class?

Answer:
Drived class can not inherit the constructor of base class but it can invoke the constructor of base class. 
in other words. :
In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class. Instead of inheriting constructors by the derived class, it is only allowed to invoke the constructor of base class.


=============================================================================
Q85. What are the difference between HttpHandler and Http Module?

Answer:
One request can have multiple HTTP Modules associated with it but can be handled by only one HTTP Handler. The type of HTTPHandler is decided by the extention of the request file like .aspx, .asmx. ASP.Net has it's own HTTPHandlers and HTTPModules that are used with client requests

=============================================================================

Q76-Q80

Q76. What is partial class in C#?
Q77. What is the difference between iqueryable (Iquerable) vs ienumerable? or AsEnumerable and AsQueryable?
Q78. Suppose you have a base class and a child class. Now while creating an instance of a child class which constructor will be called first?
Q79. What is the difference between Const and Readonly in C#?
Q80. What is finalize keyoword in C#?
=======================================================================
Q76. What is partial class in C#?

Answer:
In C#, you can split the implementation of a class, a struct, a method, or an interface in multiple .cs files using the partial keyword. The compiler will combine all the implementation from multiple .cs files when the program is compiled.

public partial class Employee
{
    public void DoWork()
    {
    }
}

public partial class Employee
{
    public void GoToLunch()
    {
    }
}

=======================================================================
Q77. What is the difference between iqueryable vs ienumerable?or AsEnumerable and AsQueryable?

Answer:
In LINQ to query data from database and collections, we use IEnumerable and IQueryable for data manipulation. IEnumerable is inherited by IQueryable, Hence IQueryable has all the features of IEnumerable and except this, it has its own features.

*As a general practice we must use IEnumerable when we are working with in memory collection(list, array) while we must use IQueryable when we are working with out of memory collections like files, database etc

IEnumerable
  1. IEnumerable exists in System.Collections Namespace.
  2. IEnumerable can move forward only over a collection, it can’t move backward and between the items.
  3. IEnumerable is best to query data from in-memory collections like List, Array, etc.
  4. While query 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.
  5. IEnumerable is suitable for LINQ to Object and LINQ to XML queries.
  6. IEnumerable supports deferred execution.
  7. IEnumerable doesn’t support custom query.
  8. IEnumerable doesn’t support lazy loading. Hence not suitable for paging like scenarios.
  9. Extension methods support by IEnumerable takes functional objects.
IQueryable
  1. IQueryable exists in System. Linq Namespace.
  2. IQueryable can move forward only over a collection, it can’t move backward and between the items.
  3. IQueryable is best to query data from out-memory (like remote database, service) collections.
  4. While query data from a database, IQueryable execute the select query on the server side with all filters.
  5. IQueryable is suitable for LINQ to SQL queries.
  6. IQueryable supports deferred execution.
  7. IQueryable supports custom query using CreateQuery and Execute methods.
  8. IQueryable support lazy loading. Hence it is suitable for paging like scenarios.
  9. Extension methods support by IQueryable takes expression objects means expression tree.
=======================================================================
Q78. Suppose you have a base class and a child class. Now while creating an instance of a child class which constructor will be called first?

Answer:
Parent constructor will be called first. 

=======================================================================
Q79. What is the difference between Const and Readonly in C#?

Answer:
Constants
1. Constants are static by default.
2. Values must be given to them at the time of declaration
3. They are compile time constant values. 

Readonly
1. Usually they are declared but value is given to them in constructor. 
2. They act as a run time constant values. Means they get their constant value during run time. 
3. Readyonly variables can be given value both during declaration and in constructor. 

=======================================================================

Q71-Q75

Q71. What is the difference between ienumerable and Ienumerator
Q72. What is the difference between AsQuerable and AsEnumerable
Q73. How to implement Role based Authorization?
Q74. What is serialization in C#?
Q75. What are web farms, web gardens and load balancers?
=====================================================================================
Q73. How to implement Role based Authorization?

Answer:

=====================================================================================
Q74. What is serialization in C#?

Answer:
Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file.
 Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

We have to provide the attribute [Serializable] on top of class which we want to serialize.

There could be multiple tricks to do the serialization:
1. JSON serialization. 
2. Binary/ XML serialization etc.

=====================================================================================
Q75. What are web farms, web gardens and load balancers?

Answer:
By default, each application pool runs with a single worker process (W3Wp.exe). When an application pool runs with multiple worker process, it is called web garden.

Advantage of Web Garden:
A Web garden share the requests which comes for that application pool and if one worker process fails to process a request then another worker process can continue to process that request.

Limitation of Web Garden:
There are some limitations with Web Garden. When you use session mode to “In Proc" with your application, it will not work properly as expected; since session will be handled by different worker process. For avoiding this issue; you should use session mode "Out Proc" having "Session State Server" or "SQL-Server Session State".




Web Farm
When a web application is hosted on multiple web servers and access based on the load on servers, it is called Web Farm.

In web farm, a single application is hosted on multiple IIS server and these IIS servers are connected with the VIP (Virtual IP) with load balancer. Load balancer IPs is exposed to external world for accessing your web application. Hence, when a request comes to server from client, it first hits the load balancer, and then based on the traffic on each server; load balancer distributes the request to the corresponding web server.

Advantage of Web Garden:
It provides high availability. If any of the web servers goes down then Load balancer redirects the incoming requests to other web servers in the web farm.

It provides high performance response for client requests.

Limitation of Web Farm:
There are some limitations with Web Farm; also. When you use session mode to “In Proc" with your application, it will not work properly as expected; since session will be handled by different web servers. For avoiding this issue; you should use session mode "Out Proc" having "Session State Server" or "SQL-Server Session State".




=====================================================================================

Q66-Q70

Q66.What is the difference between .first(), .single(), .firstorDefault in .net linq?
Q67. Difference between single and singleOrDefault in linq?
Q68. Different types of design patterns in C#?
Q69. Use of keyword Sealed in C#?
Q70. Disadvantages of late binding in C#?
-----------------------------------------------------------------------------------------------------------------------------
Q66. What is the difference between .first(), .single(), .firstorDefault in .net linq?

Answer:
var numbers = new List<int> { 10, 20, 30 };
var first = numbers.First();            // 10
var firstOrDefault = numbers.FirstOrDefault(); // 10
var single = numbers.Single();          // throws exception (more than one element)


1. .First() = If the sequence has at least one element, it returns the first one. No issues in having more than 1 element. If there are no elements it will throw error. 

2. .FirstOrDefault()n= Give me the first element, or the default value if there’s none. Default value is null for reference types and  0 for int, false for bool, etc.
it is ok for sequence to be empty. It wont throw the error but a default value. 

3. .Single() = Means the return is expected to be exact single element. if its more than 1 element it will through error. Eg fetching the particular employee ID. 

-----------------------------------------------------------------------------------------------------------------------------
Q67. Difference between single and singleOrDefault in linq?

Answer:
Both fetch the single element from the collection object or source, but Single will throw and exceptionif no element found, 

when SingleOrDefault will not throw any error, it will return the default value of that data type. Which is usually null. 

Means if you do not want exception to be thrown use. firstOrDefault() or SingleOrDefault()
-----------------------------------------------------------------------------------------------------------------------------
Q68. Different types of design patterns in C#?

Answer:
Creational, Structural, Behavioral 
  1. Behavioral - These design patterns are specifically concerned with communication between objects.
    1. Chain of responsibility design pattern. 
    2. Behaviour 
    3. Iterator 
  2. Structural - Make different pieces of systems in compatible with other part of System. 
    1. Adaptor
    2. Facade
    3. Proxy
  3. Creational - It deals with the object creation mechanism. 
    1. Singleton Design pattern
    2. Factory Design pattern
    3. Abstract Factory
-----------------------------------------------------------------------------------------------------------------------------
Q69. Use of keyword Sealed in C#?

Answer:
In c#, sealed is a keyword that is used to stop inheriting the particular class from other classes and we can also prevent overriding the particular properties or methods based on our requirements.

Real life usage. Lets say you have different subscription level in your product  eg basic, hd, fhd, uhd and u don't want uhd (ultra hd) to be further inherit by any other class u can make uhd as sealed class.  So from code reusability HD will be inherited from basic. fHD will inherit HD. And so on. every parent subscription will have all the features of its child subscription but there will be no further features above UHD as it is a sealed class.
-----------------------------------------------------------------------------------------------------------------------------
Q70. Disadvantages of late binding in C#?

Answer:
(1) program runs slow as it have to evaluate things at run time. 
(2) We don't have intelligence.
(3) We don't get error at compilation time. 
-----------------------------------------------------------------------------------------------------------------------------

Q61-Q65

Q61. Difference between Ref and Out keywords?
Q62. What are the differences between Application object and session object?
Q63. What is the difference between .tostring(), Convert.tostring()?
Q64. What is the difference between func action and predicate delegates?
Q65. Difference between covariance and variance in delegates?
-----------------------------------------------------------------------------------------------------------------------------
Q61. Difference between Ref and Out keywords?

Answer:
Both ref and out are technique to get values when we have more than one return type. Both ref and out pass value by reference. 
Ref need to be initialized before usage while Out can be used without initializing it. 

        static void Main(string[] args)
        {
            int i;
            int j;
            j = 9;
            string s = getstring(out i, ref j);
            Console.WriteLine(i);
            Console.WriteLine(j);
            Console.Read();
                    }

        private static string getstring(out int i, ref int j)
        {
            j = 6;
            i = 4;
            return "app";
        }
-----------------------------------------------------------------------------------------------------------------------------
Q62. What are the differences between Application object and session object?

Answer:
The session object is used to maintain the session of each user. If one user enter in to the application then they get session id if he leaves from the application then the session id is deleted. If they again enter in to the application they get different session id.
But for application object the id is maintained for whole application.

-----------------------------------------------------------------------------------------------------------------------------
Q63. What is the difference between .tostring(), Convert.tostring()?

Answer:
The basic difference between them is “Convert” function handles NULLS while
“.ToString()” does not it will throw a NULL reference exception error. So as a good coding practice using “convert” is always safe.
-----------------------------------------------------------------------------------------------------------------------------
Q64. What is the difference between func action and predicate delegate?

Answer:
1) The Func delegate takes zero, one or more input parameters, and returns a value (with its out parameter).

2) Action takes zero, one or more input parameters, but does not return anything.

3) Predicate is a special kind of Func. It represents a method that contains a set of criteria mostly defined inside an if condition and checks whether the passed parameter meets those criteria or not.

-----------------------------------------------------------------------------------------------------------------------------
Q65. Difference between covariance and variance in delegates?

Answer:



Q56-Q60

Q56. What is the difference between .net Standard, .net Framework and .net Core?
Q57. What are four pillars of OOPS? Explain Abstraction and Encapsulation in detail?
Q58. What is the difference between Array and Collection?
Q59. What are the two ways to prevent class from being inherited?
Q60. What is jagged Array?
-----------------------------------------------------------------------------------------------------------------------------
Q56. What is the difference between .net Standard, .net Framework and .net Core?

Answer:

-----------------------------------------------------------------------------------------------------------------------------
Q57. What are four pillars of OOPS? Explain Abstraction and Encapsulation in detail?

Answer:
Abstraction, Encapsulation, Polymorphism, and inheritance are called 4 pillars of OOPS. 

Encapsulation - Binding or encapsulating of all related data into a single unit and keep it safe from outside misuse and access. Class is an example of encapsulation. We can methods private, protected and public to protect the misuse from outside code. 

Abstraction - It means showing only the relevant information hiding the unnecessary complexity. Abstraction can be implemented by use of interface and abstract class.  By use of Interface we are telling client only the method name, parameters required and output we will receive. 
-----------------------------------------------------------------------------------------------------------------------------
Q58. What is the difference between Array and Collection?

Answer:

Difference between Array and Collection:
 
ArrayCollection
1. Array is Group of Homogeneous data type object.1. Collection is Group of Homogeneous and Heterogeneous data type object.
2. Array is fixed in size.2. Collection is not fixed in size.
3. Array is Strong type.3. Collection is not strong Type.
4. There is no boxing and unboxing process on Array4. There is process of Boxing and Unboxing on Collection.
 5.We use Generic on Collection to make Collection as Strong type

Heterogeneous collection example - ArrayList a = new ArrayList()
collections examples - ArrayList, List, Stack, ICollection, IEnumerableand IDictionary. 


-----------------------------------------------------------------------------------------------------------------------------
Q59. What are the two ways to prevent class from being inherited?

Answer:
1. Make class sealed
2. Make class constructor private. 

-----------------------------------------------------------------------------------------------------------------------------
Q60. What is jagged Array?

Answer:
Array of Array is known as jagged array. 

Below is the example of jagged Array. 

int[][] jaggedArray = new int[3][];

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

Q51-Q55

Q51. What is the difference between for loop and Foreach loop in C#? Which has better performance and why?
Q52. When to choose readonly and when to choose constant?
Q53. Good coding practices in C#?
Q54. What is cyclomatic complexity in programming?
Q55. What is Big O notation?

=======================================================================================
Q51. What is the difference between for loop and Foreach loop in C#? Which has better performance and why?

Answer:
For loop is just a iteration loop and can be used for anything while foreach loop is only designed to work on collections. 

Performance or speed wise for loop is almost similar to ForEach loop but theoretically for loop is better in performance. 
=======================================================================================
Q52. When to choose readonly and when to choose constant?

Answer:
When you want to make something static during compile time and you do not want this value get hampered anywhere in code make it Constant. 

Constants are static by default. Constant give better performance as they are defined in memory at compile time only. 

Readonly are required when you have your constants at run time only for eg. you get something related to claims during run time from the client whom initializes the class and once you have the data you do not want it to get changed in future than you can use read-only. 

Readonly has a little overhead of getting value during run time but has advantage of defining value at run time which is not possible in case of Constant. 

=======================================================================================
Q53. Good coding practices in C#?

Answer:
1. Code must have proper error handling. 
2. Proper logging
3. Good coding practices tool like Sonar must be integrated. 
4. Good naming convention must be used. 
5. Proper comments must be present. 
6. Null, empty, undefined check must be present where ever possible. 
7. While comparing string either bring both string into lowercase or into upper case.
8. Make proper usage of access modifiers. We must not make blindly everything public. 
9. Make use of Interface as it bring dependency injection in picture. 
10. When working on un managed code, we must remember to dispose un managed code. 
11. Make use of authentication filter or middleware

=======================================================================================
Q54. What is cyclomatic complexity in programming?

Answer:
software metric used to determine the complexity of a program. It is a count of the number of decisions in the source code. The higher the count, the more complex the code.
IF-else, is a great example of this. 

=======================================================================================
Q55. What is Big O  notation?

Answer:

Big O notation shows the number of operations

O(log n) Binary search
O(n) Simple search
O(n * log n) Quicksort
O(n2) Selection sort
O(n!) Traveling salesperson