Questions Answers (OOPs, C#, DB Interview)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

Q: Difference between WHERE vs.

HAVING clause
A: 1. WHERE clause is used for filtering rows and it applies on each and every row, while HAVING clause is used to filter groups
in SQL.
2. When WHERE and HAVING clauses are used together in a SELECT query with aggregate function, WHERE clause is applied
first on individual rows and only rows which pass the condition are included for creating groups. Once a group is created, HAVING
clause is used to filter groups based upon the condition specified.

Q: What is .NET Core?


A: .NET core is a free, cross-platform, open source developer platform for building many different types of applications. With .NET,
you can use multiple languages, editors, and libraries to build for web, mobile, desktop, gaming, and IoT.

Q: What is the difference between an SQL query and a stored procedure


A: Queries need to be compiled each and every time when we execute, whereas when we execute Stored Procedures (SP) for
the first time, SP will be compiled only once and the execution plans are cached in memory. No need to compile every time, in this
way, recompilation is not necessary.

Q: Data Definition Language (DDL)


A: DDL is the short name of Data Definition Language, which deals with database schemas and descriptions of how the data
should reside in the database.
CREATE – to create a database and its objects like (table, index, views, store procedure, function and triggers).
ALTER – alters the structure of the existing database.
DROP – delete objects from the database.
TRUNCATE – remove all records from a table, including all spaces allocated for the records are removed.
COMMENT – add comments to the data dictionary.
RENAME – rename an object.

Q: Data Manipulation Language (DML)


A: DML is short name of Data Manipulation Language which deals with data manipulation, and includes most common SQL
statements such as SELECT, INSERT, UPDATE, DELETE etc, and it is used to store, modify, retrieve, delete and update data in
database.
SELECT – retrieve data from a database.
INSERT – insert data into a table.
UPDATE – updates existing data within a table.
DELETE – Delete all records from a database table.
MERGE – UPSERT operation (insert or update).
CALL – call a PL/SQL or Java subprogram.
EXPLAIN PLAN – interpretation of the data access path.
LOCK TABLE – concurrency Control.

Q: Data Control Language (DCL)


A: DCL is short name of Data Control Language includes commands such as GRANT, and mostly concerns with rights,
permissions and other controls of the database system.
GRANT – allow users e access privileges to database
REVOKE – withdraw users access privileges given by using the GRANT command

Q: Transaction Control Language (TCL)


A: TCL is short name of Transaction Control Language which deals with transaction within a database.
COMMIT – commits a Transaction
ROLLBACK – rollback a transaction in case of any error occurs
SAVEPOINT – to rollback the transaction making points within groups
SET TRANSACTION – specific characteristics for the transaction

.Net Interview Questions


Q: Difference between Abstract Class and Interface in C#
A:
Abstract Class Interface

An abstract class can have all access modifiers for member An interface is not allowed to have access modifiers for
declaration of functions, subs, and properties. member declaration of functions, subs, properties, etc. All the
members are assumed as implicitly public.

A class can at most use only one abstract class. A class may inherit any number of interfaces.

Multiple inheritance is not supported in abstract class. An interface may support multiple inheritance.

Members of an abstract class cannot be static unless it’s a Members of an interface cannot be static.
Complete Member.

It can have constructor declaration. It cannot have a constructor declaration.

An abstract class has pre-defined fields and constraints. Fields cannot be defined in interfaces.

It can have both abstract and non-abstract methods. It can only have abstract methods.

Q: State Management in ASP.Net?


A: Two Types of State Management techniques are available in ASP.NET as in the following.
1) Server side-
Session- Session is a very important technique to maintain state. Normally session is used to store information and identity.
The server stores information using Sessionid.
Types of Session- 1)Session Start 2) Session End
Application- Application State is a server side management state. It is also called application level state management. In this
mainly store user activity in server memory and application event shown in Global.asax file.
Types of Application- 1)Application Start 2) Application Error 3) Application End
Cache- Cache is stored on server side. It implements Page Caching and data caching. Cache is use to set expiration policies.
2) Client Side-

Cookie- Cookie is a small and an important part of ASP.NET. In this store user information, session and application. It can be
created constant and temporary and they work with browser request. Cookies are stored on client side. The server can read
cookies and abstract data.

Types Cookie:- 1) Persistence- This type of cookie works with Date and time. 2)Non-Persistence- This is a temporary cookie. It
is created with access application and discards the close application.
Control state- Control state technique is developed to maintain data work properly in order. We can use view state but
suppose view state is disabled by the user, the control will not work as expected. For expected results of the control we have to
use Control State. In application, the Viewstate is by default true. Sometimes we need to use custom control to manage
application properly.
Hidden Field- Hidden fields are used to store value to client side. Hidden field is not displayed on the browser, but it works on
a request.
Viewstate- Viewstate is a very useful client side property. It is used for page level state management. Viewstate stores any
type of data and used for sending and receiving information.
Query String- Query string stores the value in URL.

Q: Difference between SessionState and ViewState in asp.net ?


A:

SessionState ViewState

If you want to store information that you want to access If you want to store information that you want to access
on different pages then you can use SessionState. only with in the page(same page) then you can use
ViewState.

SessionState is saved on the server. ViewState is saved in the page.

Data stored in the SessionState will be cleared when the Data stored in the ViewState will send back to the server
session expired(usually after 20 min of inactivity when when postback action performed (no expiration).
using session inproc).

SessionState is used to save the user specific data like ViewState is used primarily by Server controls to retain
UserID, User Role, etc state only on pages that post data back to themselves. And
when you want to save the page level data you can use
ViewState

Q: What are Stages of asp.net page life cycle ?


1.Page request >>> 2.Starting of page life cycle >>> 3. Page initialization >>> 4. Page load >>> 5. Validation >>>
6. Postback event handling >>> 7.Page rendering >>> 8. Unload.

Q: What are page life cycle events?


PreInit >>> Init >>> InitComplete >>> LoadViewState >>> LoadPostData >>> PreLoad >>> Load >>> LoadComplete >>>
PreRender >>> PreRenderComplete >>> SaveStateComplete >>> UnLoad

For more details: https://www.c-sharpcorner.com/UploadFile/8911c4/page-life-cycle-with-examples-in-Asp-Net/

Q: Can multiple catch blocks be executed?


A: No, Multiple catch blocks can't be executed. Once the proper catch code is executed, the control is transferred to the finally
block and then the code that follows the finally block gets executed.

Q: What is the difference between public, static and void?


A: Public declared variables or methods are accessible anywhere in the application. Static declared variables or methods are
globally accessible without creating an instance of the class. Static members are by default not globally accessible; it depends
upon the type of access modifier used. The compiler stores the address of the method as the entry point and uses this information
to begin execution before any objects are created. And Void is a type modifier that states that the method or variable does not
return any value.

Q: Describe the accessibility modifier "protected internal".


A: Protected Internal variables/methods are accessible within the same assembly and also from the classes that are derived
from this parent class.

Q: What are the differences between System.String and System.Text.StringBuilder classes?


A: System.String is immutable. When we modify the value of a string variable then a new memory is allocated to the new value
and the previous memory allocation released. System.StringBuilder was designed to have the concept of a mutable string where a
variety of operations can be performed without allocation separate memory location for the modified string.

Q: What's the difference between an interface and an abstract class?


A: Interfaces have all the methods having only declaration but no definition. In an abstract class, we can have some concrete
methods. In an interface class, all the methods are public. An abstract class may have private methods.

Q: What is the difference between Finalize() and Dispose() methods?


A: Dispose() is called when we want for an object to release any unmanaged resources with them. On the other hand Finalize() is
used for the same purpose but it doesn't assure the garbage collection of an object.

Q: What are delegates?


A: Delegates are same as function pointers in C++ but the only difference is that they are type safe unlike function pointers.
Delegates are required because they can be used to write much more generic type safe functions.
A delegate(known as function pointer in C/C++) is a references type that invokes single/multiple method(s) through the delegate
instance. It holds a reference of the methods. Delegate types are sealed and immutable type.
There are three types of delegates that can be used in C#.
1)Single Delegate :-Single delegate can be used to invoke a single method.
2)Multicast Delegate :- Multicast delegate can be used to invoke the multiple methods. The delegate instance can do
multicasting (adding new method on existing delegate instance) using the + operator and – operator can be used to remove a
method from a delegate instance. All methods will invoke in sequence as they are assigned.
3)Generic Delegate

Q: What is the base class in .net from which all the classes are derived from?
A: System.Object

Q: Is C# code is managed or unmanaged code?


A: C# is managed code Common language runtime can compile C# code to Intermediate language.

Q: difference between Server.Transfer() and Response.Redirect()?


A: Response.Redirect()-
1) The Response.Redirect() method redirects a request to a new URL and specifies the new URL
2) Response.Redirect() sends an HTTP request to the browser, then the browser sends that request to the web server, then
the web server delivers a response to the web browser.
3) Response.Redirect() can be used for both .aspx and HTML pages
4) Response.Redirect() method the previous page is removed from server memory and loads a new page in memory.
Server.Transfer()-
1) Server.Transfer() method for the current request, terminates execution of the current page and starts execution of a new
page using the specified URL path of the page
2) Server.Transfer() sends a request directly to the web server and the web server delivers the response to the browser.
3) Server.Transfer() can be used only for .aspx pages and is specific to ASP and ASP.NET
4) When you use Server.Transfer() then the previous page also exists in server memory

Q: What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?


A: ExecuteScalar()-
1) ExecuteScalar is typically used when your query returns a single value. If it returns more, then the result is the first column
of the first row.
2) ExecuteScalar will work with Non-Action Queries that contain aggregate functions.
3) Return the first row and first column value of the query result.
4) Return type is object.
5) Return value is compulsory and should be assigned to a variable of required type
ExecuteReader()-
1) ExecuteReader is used for any result set with multiple rows/columns
2) ExecuteReader will work with Action and Non-Action Queries (Select)
3) Returns the collection of rows selected by the Query.
4) Return type is DataReader
5) Return value is compulsory and should be assigned to another object DataReader.
ExecuteNonQuery()-
1) ExecuteNonQuery does not return data at all: only the number of rows affected by an insert, update, or delete.
2) It will work with Action Queries only (Create,Alter,Drop,Insert,Update,Delete).
3) Returns the count of rows affected by the Query.
4) Return type is int
5) Return value is optional and can be assigned to an integer variable.

Q: Difference Between DataReader, DataSet, DataAdapter and DataTable in C#


A:
DataReader-
DataReader is used to read the data from database and it is a read and forward only connection oriented architecture during fetch
the data from database. DataReader will fetch the data very fast when compared with dataset. Generally we will use
ExecuteReader object to bind data to datareader.
-Holds the connection open until you are finished (don't forget to close it!).
-Can typically only be iterated over once
-Is not as useful for updating back to the database
DataSet-
DataSet is a disconnected orient architecture that means there is no need of active connections during work with datasets and it is
a collection of DataTables and relations between tables. It is used to hold multiple tables with data. You can select data from
tables, create views based on table and ask child rows over relations. Also DataSet provides you with rich features like saving
data as XML and loading XML data.
DataAdapter-
DataAdapter will acts as a Bridge between DataSet and database. This dataadapter object is used to read the data from database
and bind that data to dataset. Dataadapter is a disconnected oriented architecture.
-Lets you close the connection as soon it's done loading data, and may even close it for you automatically
-All of the results are available in memory
-You can iterate over it as many times as you need, or even look up a specific record by index
-Has some built-in faculties for updating back to the database.
DataTable
DataTable represents a single table in the database. It has rows and columns. There is not much difference between dataset and
datatable, dataset is simply the collection of datatables.

Q: What is a View? Can we insert,Update and delete a view?


A: A view is a collection of different tables data in one table .
Yes it is possible, we can perform CRUD operations in a basic view i.e single table view but if its a complex view, we can’t perform
those CRUD operations.

Q:What is the Difference Between String and StringBuffer?


A:
String StringBuffer

String class is immutable StringBuffer class is mutable (modifiable)

Consumes more memory during concatenation Consumes less memory during concatenation

Slow performance Fast performance

Overrides equals() and hashcode() methods of the object Doesn't override the equals() and hashcode() methods of the
class object class

eg: eg:

1. String str = “Hello folks”; 1. StringBuffer str = new StringBuffer(“Good”);


2. Str = “Smile”; 2. Str.append(“night”);

Q:What is the Difference Between STRUCTURE and class?


A:
Class STRUCTURE

Classes are of reference types. Structs are value types.

All the reference types are allocated on the heap memory. All the value types are allocated on stack memory.

Allocation of large reference type is cheaper than allocation of Allocation and deallocation is cheaper in value type as
large value type. compared to reference type.
Class has limitless features. Struct has limited features.

Class is generally used in large programs. Struct are used in small programs.

Classes can contain constructor or destructor. Structure does not contain constructor or destructor.

Classes used new keyword for creating instances. Struct can create an instance, without new keyword.

A Class can inherit from another class. A Struct is not allowed to inherit from another struct or class.

The data member of a class can be protected. The data member of struct can’t be protected.

Function member of the class can be virtual or abstract. Function member of the struct cannot be virtual or abstract.

Two variables of class can contain the reference of the same Each variable in struct contains its own copy of data(except in
object and any operation on one variable can affect another ref and out parameter variable) and any operation on one
variable. variable can not affect another variable.

Oops Concept In Asp.Net

Class :-
In OOP languages it is mandatory to create a class for representing data.
A class is a blueprint of an object that contains variables for storing data and functions to perform operations on the data.
A class will not occupy any memory space and hence it is only a logical representation of data.
To create a class, you simply use the keyword "class" followed by the class name:
Ex:- Class Employee
{

Object :-
"An object is an instance of a class"
A class will not occupy any memory space. Hence to work with the data represented by the class you must create a variable for
the class, that is called an object.
When an object is created using the new operator, memory is allocated for the class in the heap, the object is called an instance
and its starting address will be stored in the object in stack memory.
When an object is created without the new operator, memory will not be allocated in the heap, in other words an instance will not
be created and the object in the stack contains the value null.
When an object contains null, then it is not possible to access the members of the class using that object.
Syntax :- Employee objEmp = new Employee();
Abstraction:-
Abstraction is "To represent the essential feature without representing the background details."
Abstraction lets you focus on what the object does instead of how it does it.
Abstraction provides you a generalized view of your classes or objects by providing relevant information.
Abstraction is the process of hiding the working style of an object, and showing the information of an object in an understandable
manner.
Real-world Example of Abstraction
Suppose you have an object Mobile Phone.
Abstraction means putting all the variables and methods in a class that are necessary.
For example: Abstract class and abstract method.
Abstraction is a common thing.

Encapsulation:-
Wrapping up a data member and a method together into a single unit (in other words class) is called Encapsulation.
Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data related to an object into that
object.
Encapsulation is like your bag in which you can keep your pen, book etcetera. It means this is the property of encapsulating
members and functions.
Encapsulation means hiding the internal details of an object, in other words how an object does something.
Encapsulation prevents clients from seeing its inside view, where the behaviour of the abstraction is implemented.
Encapsulation is a technique used to protect the information in an object from another object.
Hide the data for security such as making the variables private, and expose the property to access the private data that will
be public.

Inheritance:-
Acquiring (taking) the properties of one class into another class is called inheritance. Inheritance provides reusability by allowing
us to extend an existing class.
The reason behind OOP programming is to promote the reusability of code and to reduce complexity in code and it is possible by
using inheritance.

The following are the types of inheritance in C#.


1)Single 2)Hierarchical 3)Multilevel 4)Multiple inheritance using Interfaces
Single inheritance :-
It is the type of inheritance in which there is one base class and one derived class.
Ex :- class A(base class)
{
}

Class B:A (derived class)


{
}
Hierarchical inheritance :-
This is the type of inheritance in which there are multiple classes derived from one base class. This type of inheritance is
used when there is a requirement of one class feature that is needed in multiple classes.
Ex:- class A(base class)
{

Class B:A
{
}

Class C:A
{
}

Class D:A
{
}

Multilevel inheritance:-
When one class is derived from another derived class then this type of inheritance is called multilevel inheritance.
Ex:- class A
{
}
Class B:A
{
}
Class C:B
{
}

Multiple inheritance using Interfaces :-


C# does not support multiple inheritances of classes. To overcome this problem we can use interfaces.
Ex:- interface A
{
}
Interface B
{
}
Class C:A,B
{
}
The following are some key points about inheritance:

1. C# does not support multiple inheritances of classes, the same thing can be done using interfaces.
2. Private members are not accessed in a derived class when one class is derived from another.
Polymorphism:-
Polymorphism is a Greek word meaning "One name many forms". In other words, one object has many forms or has one
name with multiple functionalities. "Poly" means many and "morph" means forms. Polymorphism provides the ability to class
multiple implementations with the same name. It is one principle concept in Object Oriented Programming after encapsulation and
inheritance.
There are basically the following two types of polymorphism in C#:

● Static / Compile Time Polymorphism.


● Dynamic / Runtime Polymorphism.

Static or Compile Time Polymorphism


It is also known as Early Binding. Method overloading and operator overloading is an example of Static Polymorphism. In
Overloading,

Method overloading:-
the method / function has the same name but different signatures. It is also known as Compile Time Polymorphism because the
decision of which method is to be called is made at compile time. Overloading is the concept in which method names are the
same with a different set of parameters.

Here the compiler checks the number of parameters passed and the type of parameter and make the decision of which method to
call and it throw an error if no matching method is found.

In the following example, the class has two methods with the same name "Add" but with different input parameters (the first
method has three parameters and the second method has two parameters).
1. public class TestData
2. {
3. public int Add(int a, int b, int c)
4. {
5. return a + b + c;
6. }
7. public int Add(int a, int b)
8. {
9. return a + b;
10. }
11. }
12. class Program
13. {
14. static void Main(string[] args)
15. {
16. TestData dataClass = new TestData();
17. int add2 = dataClass.Add(45, 34, 67);
18. int add1 = dataClass.Add(23, 34);
19. }
20. }

Operator overloading:-

Dynamic / Runtime Polymorphism:-


Dynamic / runtime polymorphism is also known as late binding. Here, the method name and the method signature (number of
parameters and parameter type must be the same and may have a different implementation). Method overriding is an example of
dynamic polymorphism.

1. public class Drawing


2. {
3. public virtual double Area()
4. {
5. return 0;
6. }
7. }
8.
9. public class Circle : Drawing
10. {
11. public double Radius { get; set; }
12. public Circle()
13. {
14. Radius = 5;
15. }
16. public override double Area()
17. {
18. return (3.14) * Math.Pow(Radius, 2);
19. }
20. }
21.
22. public class Square : Drawing
23. {
24. public double Length { get; set; }
25. public Square()
26. {
27. Length = 6;
28. }
29. public override double Area()
30. {
31. return Math.Pow(Length, 2);
32. }
33. }
34.
35. public class Rectangle : Drawing
36. {
37. public double Height { get; set; }
38. public double Width { get; set; }
39. public Rectangle()
40. {
41. Height = 5.3;
42. Width = 3.4;
43. }
44. public override double Area()
45. {
46. return Height * Width;
47. }
48. }
49.
50. class Program
51. {
52. static void Main(string[] args)
53. {
54.
55. Drawing circle = new Circle();
56. Console.WriteLine("Area :" + circle.Area());
57.
58. Drawing square = new Square();
59. Console.WriteLine("Area :" + square.Area());
60.
61. Drawing rectangle = new Rectangle();
62. Console.WriteLine("Area :" + rectangle.Area());
63. }
64. }

The compiler requires an Area() method and it compiles successfully but the right version of the Area() method is not being
determined at compile time but determined at runtime. Finally the overriding methods must have the same name and signature
(number of parameters and type), as the virtual or abstract method defined in the base class method and that it is overriding in the
derived class.

A method or function of the base class is available to the child (derived) class without the use of the "overriding" keyword. The
compiler hides the function or method of the base class. This concept is known as shadowing or method hiding.

Q:What is LINQ?
A: The full form of LINQ is Language Integrated Query . It was introduced in .NET 3.5 and we can use it in C# or VB.NET based
on our requirements. LINQ can be used to query data from different data sources such as Collections, Generics, XML Documents,
ADO.NET Datasets, SQL Databases, Web-service etc. and It connects UI and data access layer.
Linq, as it appears in the System.Linq namespace and its a set of extension methods that allow you to query collections directly in
code. LINQ is an acronym for "Language Integrated Query". LINQ adds a rich, standardized query syntax in .NET programming
languages that allows developers to interact with any type of data.

Why we need to use LINQ?


Now the question arise why should we use LINQ? What’s so different in LINQ that everyone would want to use it in their
application and not the SQL? Well the answer is quite simple as LINQ is simpler, tidier, and higher-level than SQL. When it comes
to querying databases, LINQ is in most cases a significantly more productive querying language than SQL.

Also we have benefit of intellisense as linq query is written in code behind and moreover it has full type checking at compile time.
So this helps us to avoid runtime errors as we can catch any error in compile time itself.
Advantages of LINQ
Following are the advantages of using linq in our applications.

1. It has full type checking at compile time.


2. It has intellisense so we can avoid silly errors.
3. Its query can be reused.
4. We can debug it using .NET debugger.
5. It supports filtering, sorting, ordering, grouping with much less effort.

Disadvantages of LINQ
Following are the drawbacks of using linq in our applications.

1. Since it is written in the code so we cannot make use of Cache execution plan which is a SQL feature as we do in stored
procedure.
2. Writing complex queries in LINQ is a bit tedious as compared to SQL.
3. If the query is not written properly then performance is degraded.
4. We have to build the project and deploy the DLL every time some change is done in the query.

Q:What is ASP.Net Life cycle:


A: ASP.Net Application Life Cycle:

1) Application Start - The life cycle of an ASP.NET application starts when a request is made by a user. This request is to the
Web server for the ASP.Net Application. This happens when the first user normally goes to home page for the application for the
first time. During this time, there is a method called Application_start which is executed by the web server. Usually, in this method,
all global variables are set to their default values.
2) Object creation - The next stage is the creation of the HttpContext, HttpRequest & HttpResponse by the web server. The
HttpContext is just the container for the HttpRequest and HttpResponse objects. The HttpRequest object contains information
about the current request, including cookies and browser information. The HttpResponse object contains the response that is sent
to the client.
3) HttpApplication creation - This object is created by the web server. It is this object that is used to process each subsequent
request sent to the application. For example, let's assume we have 2 web applications. One is a shopping cart application, and the
other is a news website. For each application, we would have 2 HttpApplication objects created. Any further requests to each
website would be processed by each HttpApplication respectively.
4) Dispose - This event is called before the application instance is destroyed. During this time, one can use this method to
manually release any unmanaged resources.
aàalĺlllllĺlď5) Application End - This is the final part of the application. In this part, the application is finally unloaded from memory.

ASP.Net Page Life Cycle:


1. Page Request- This is when the page is first requested from the server. When the page is requested, the server checks if
it is requested for the first time. If so, then it needs to compile the page, parse the response and send it across to the user.
If it is not the first time the page is requested, the cache is checked to see if the page output exists. If so, that response is
sent to the user.
2. Page Start – During this time, 2 objects, known as the Request and Response object are created. The Request object is
used to hold all the information which was sent when the page was requested. The Response object is used to hold the
information which is sent back to the user.
3. Page Initialization – During this time, all the controls on a web page is initialized. So if you have any label, textbox or any
other controls on the web form, they are all initialized.
4. Page Load – This is when the page is actually loaded with all the default values. So if a textbox is supposed to have a
default value, that value is loaded during the page load time.
5. Validation – Sometimes there can be some validation set on the form. For example, there can be a validation which says
that a list box should have a certain set of values. If the condition is false, then there should be an error in loading the
page.
6. Postback event handling – This event is triggered if the same page is being loaded again. This happens in response to an
earlier event. Sometimes there can be a situation that a user clicks on a submit button on the page. In this case, the same
page is displayed again. In such a case, the Postback event handler is called.
7. Page Rendering – This happens just before all the response information is sent to the user. All the information on the form
is saved, and the result is sent to the user as a complete web page.
8. Unload – Once the page output is sent to the user, there is no need to keep the ASP.net web form objects in memory. So
the unloading process involves removing all unwanted objects from memory.

Q:What are different JOINS used in SQL?


A:A JOIN clause is used to combine rows from two or more tables, based on a related column between them.

● (INNER) JOIN: Returns records that have matching values in both tables
● LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table
● RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table
● FULL (OUTER) JOIN: Return all records when there is a match in either left or right table

Q:What is Normalization?

A: Normalization is a database design technique which organizes tables in a manner that reduces redundancy and dependency
of data.It divides larger tables to smaller tables and links them using relationships.

Theory of Data Normalization in SQL is still being developed further. For example, there are discussions even on 6th Normal
Form. However, in most practical applications, normalization achieves its best in 3rd Normal Form. The evolution of Normalization
theories is illustrated below

Assume a video library maintains a database of movies rented out. Without any normalization, all information is stored in one table
as shown below.
Here you see Movies Rented column has multiple values.

1NF (First Normal Form) Rules:

● Each table cell should contain a single value.


● Each record needs to be unique.

The above table in 1NF-

1NF Example

Before we proceed let's understand a few things --

What is a KEY?

A KEY is a value used to identify a record in a table uniquely. A KEY could be a single column or combination of multiple columns

Note: Columns in a table that are NOT used to identify a record uniquely are called non-key columns.
What is a Primary Key?

A primary is a single column value used to identify a database record uniquely.

It has following attributes

● A primary key cannot be NULL


● A primary key value must be unique
● The primary key values cannot be changed
● The primary key must be given a value when a new record is inserted.

What is Composite Key?

A composite key is a primary key composed of multiple columns used to identify a record uniquely

In our database, we have two people with the same name Robert Phil, but they live in different places.

Hence, we require both Full Name and Address to identify a record uniquely. That is a composite key.

Let's move into second normal form 2NF

2NF (Second Normal Form) Rules

● Rule 1- Be in 1NF
● Rule 2- Single Column Primary Key

It is clear that we can't move forward to make our simple database in 2nd Normalization form unless we partition the table above.
Database - Foreign Key

In Table 2, Membership_ID is the Foreign Key

Foreign Key references the primary key of another Table! It helps connect your Tables

● A foreign key can have a different name from its primary key
● It ensures rows in one table have corresponding rows in another
● Unlike the Primary key, they do not have to be unique. Most often they aren't
● Foreign keys can be null even though primary keys can not
Why do you need a foreign key?
Suppose an idiot inserts a record in Table B such as
You will only be able to insert values into your foreign key that exist in the unique key in the parent table. This helps in referential
integrity.

The above problem can be overcome by declaring membership id from Table2 as foreign key of membership id from Table1
Now, if somebody tries to insert a value in the membership id field that does not exist in the parent table, an error will be shown!
What are transitive functional dependencies?

A transitive functional dependency is when changing a non-key column, might cause any of the other non-key columns to change
Consider the table 1. Changing the non-key column Full Name may change Salutation.

3NF (Third Normal Form) Rules

● Rule 1- Be in 2NF
● Rule 2- Has no transitive functional dependencies

To move our 2NF table into 3NF, we again need to again divide our table.

3NF Example

We have again divided our tables and created a new table which stores Salutations.
There are no transitive functional dependencies, and hence our table is in 3NF
In Table 3 Salutation ID is primary key, and in Table 1 Salutation ID is foreign to primary key in Table 3

Boyce-Codd Normal Form (BCNF)


Even when a database is in 3rd Normal Form, still there would be anomalies resulted if it has more than one Candidate Key.
Sometimes is BCNF is also referred as 3.5 Normal Form.

4NF (Fourth Normal Form) Rules


If no database table instance contains two or more, independent and multivalued data describing the relevant entity, then it is in
4th Normal Form.

5NF (Fifth Normal Form) Rules


A table is in 5th Normal Form only if it is in 4NF and it cannot be decomposed into any number of smaller tables without loss of
data.

6NF (Sixth Normal Form) Proposed


6th Normal Form is not standardized, yet however, it is being discussed by database experts for some time. Hopefully, we would
have a clear & standardized definition for 6th Normal Form in the near future...

Q:What is a static class?


A: A static class is similar to normal class with these differences
1. Contains only static members means all the methods and members must be static
2. Cannot be instantiated by using new keyword
3. By default it is sealed class and therefore cannot be inherited.
4. It can have default constructor or
5. Can have only one constructor without any parameters
6. Access modifiers are not allowed on static constructors
7. Cannot have instantiate constructors
8. Methods can be called by using class name dot (.) method name.

EXAMPLE
public static class MyStaticClass
{
public static int myStaticVariable = 0;
public static void MyStaticMethod()
{
Console.WriteLine("This is a static method.");
}
public static int MyStaticProperty { get; set; }
}
class Program
{
Static void Main(string[]args)
{
Console.WriteLine(MyStaticClass.myStaticVariable); MyStaticClass.MyStaticMethod();
MyStaticClass.MyStaticProperty=100; Console.WriteLine(MyStaticClass.MyStaticProperty);
}
}

OUTPUT:
0
This is a static method.
100

In the above example, MyStaticClass is a static class with static variable, method and property. All the static members can be
access using class Name without creating an object of a class e.g. MyStaticClass.MyStaticMethod().
It is also possible to have static members in non-static classes just like a normal class. You can instantiate non static classes
using the new keyword as usual. However, the instance variable can only access the non-static methods and variables, it cannot
access the static methods and variables.

For example, consider the following myNonStaticClass with mix of static and non-static methods:
public class MyNonStaticClass
{
private static int myStaticVariable = 0;
public static void MyStaticMethod()
{
Console.WriteLine("This is static method.");
}
public void myNonStaticMethod()
{
Console.WriteLine("Non-static method");
}
}

In the above example, MyNonStaticClass can be instantiated and access the non-static members. However,
you cannot access static members. The following figure shows the debug view.
C# Static Constructor
A static or non-static class can have a static constructor without any access modifiers like public, private,
protected, etc.
A static constructor in a non-static class runs only once when the class is instantiated for the first time.
A static constructor in a static class runs only once when any of its static members accessed for the first
time.
public static class MyStaticClass
{
static MyStaticClass()
{
Console.WriteLine("Inside static constructor.");
}
public static int myStaticVariable = 0;
public static void myStaticMethod()
{
Console.WriteLine("This is static method.");
}
public static int MyStaticProperty { get; set; }
}
class Program
{
static void Main(string[] args)
{
MyStaticClass.myStaticVariable = 100;
MyStaticClass.MyStaticProperty = 200;
MyStaticClass.myStaticVariable = 300;
MyStaticClass.MyStaticProperty = 400;
}
}
OUTPUT:
Inside static constructor.
In the above example, the static members was accessed multiple times. However, static constructor got
called only once when any of its static members was accessed for the first time.

Example: Static constructor in a non-static class

public class MyNonStaticClass


{
static MyNonStaticClass()
{
Console.WriteLine("Inside static constructor.");
}
public void myNonStaticMethod()
{
Console.WriteLine("Non-static method");
}
}
class Program
{
static void Main(string[] args)
{
MyNonStaticClass mnsObj1 = new MyNonStaticClass();
MyNonStaticClass mnsObj2 = new MyNonStaticClass();
MyNonStaticClass mnsObj3 = new MyNonStaticClass();
}
}

OUTPUT:
Inside static constructor

In the above example, we instantiate MyNonStaticClass three times but the static constructor got called only once when it
instantiated for the first time.

Q:What is Authentication and Authorization ?


A:Authentication :
1.Authentication is the process of verifying your login username and password.
2.Authentication is the process of obtaining some sort of credentials from the users and using those credentials to verify the
user's identity
3.Authentication is about validating your credentials like User Name/User ID and password to verify your identity.
4.The system determines whether you are what you say you are using your credentials. In public and private
networks, the system authenticates the user identity via login passwords.
5.For example, when you enter your ATM card into the ATM machine, the machine asks you to enter your pin. After
you enter the pin correctly, the bank then confirms your identity that the card really belongs to you and you’re the
rightful owner of the card. By validating your ATM card pin, the bank actually verifies your identity, which is called
authentication. It merely identifies who you are, nothing else.
Authorization :
1.Authorization is the process of verifying that you can access to something.
2. Authorization is the process of allowing an authenticated user access to resources.
3.Authorization is the process to determine whether the authenticated user has access to the particular resources. It
verifies your rights to grant you access to resources such as information, databases, files, etc. Authorization usually
comes after authentication which confirms your privileges to perform.
4.For example, the process of verifying and confirming employees ID and passwords in an organization is called
authentication, but determining which employee has access to which floor is called authorization.

Differance:

Authentication Authorization

Authentication confirms your identity to grant access to Authorization determines whether you are authorized to
the system. access the resources.

It is the process of validating user credentials to gain It is the process of verifying whether access is allowed or
user access. not.

It determines whether user is what he claims to be. It determines what user can and cannot access.

Authentication usually requires a username and a Authentication factors required for authorization may
password. vary, depending on the security level.

Authentication is the first step of authorization so always Authorization is done after successful authentication.
comes first.

For example, students of a particular university are For example, authorization determines exactly what
required to authenticate themselves before accessing information the students are authorized to access on the
the student link of the university’s official website. This is university website after successful authentication.
called authentication.

Q:What is CLI?
A: A command-line interface or command language interpreter (CLI), also known as command-line user interface, console user
interface[1] and character user interface (CUI), is a means of interacting with a computer program where the user (or client) issues
commands to the program in the form of successive lines of text (command lines). A program which handles the interface is called
a command language interpreter or shell (computing).

Q:How to select next 10 record from sql table?


A: Using ROW_NUMBER() we can select
eg:-
select tbl1.R_No,tbl1.RegName,tbl1.MobileNo from
(select RegName,MobileNo, (ROW_NUMBER() over( order by(RegId) )) as R_No
from UserRegistrationInfo
) as tbl1
where tbl1.R_No between 11 and 13

Waiting for another solution

If any one have another solution then put it here…..

Q. What is Serialization?
A: Serialization is the process of bringing an object into a form that it can be written on stream. It's the process of
converting the object into a form so that it can be stored on a file, database, or memory; or, it can be transferred
across the network. Its main purpose is to save the state of the object so that it can be recreated when needed.
Q. What is Deserialization ?
A: As the name suggests, deserialization is the reverse process of serialization. It is the process of getting back the
serialized object so that it can be loaded into memory. It resurrects the state of the object by setting properties, fields
etc.

Types :-
1)Binary Serialization
2)XML Serialization
3)JSON Serialization

Q. Ref And Out Different.

Ref Out

The parameter or argument must be initialized first It is not compulsory to initialize a parameter or argument
before it is passed to ref. before it is passed to an out.

It is not required to assign or initialize the value of a A called method is required to assign or initialize a value
parameter (which is passed by ref) before returning to of a parameter (which is passed to an out) before
the calling method. returning to the calling method.

Passing a parameter value by Ref is useful when the Declaring a parameter to an out method is useful when
called method is also needed to modify the pass multiple values need to be returned from a function or
parameter. method.

It is not compulsory to initialize a parameter value before A parameter value must be initialized within the calling
using it in a calling m weethod. method before its use.
When we use REF, data can be passed bi-directionally. When we use OUT data is passed only in a
unidirectional way (from the called method to the caller
method).

Q.Namespace and Assembly ?


Ans :- A .Net Namespace provides the fundamental unit of logical code grouping while an assembly
provides a fundamental unit of physical code grouping.

Namespace

Namespaces is a logical group of related classes that can be used by any other language targeting the
Microsoft .Net framework . It is more used for logical organization of your classes. Namespaces are a way of
grouping type names and reducing the chance of name collisions.

Hierarchy and Fully-Qualified Names

The fully qualified name of a class is constructed by concatenating the names of all the namespaces that
contain the type. For e.g. the fully qualified name of the TextBox class is System.Windows.Forms.TextBox .
That means TextBox class is contained in the Forms namespace that is contained in the Windows
namespace that is contained in the root System namespace.

Textbox namespace Hierarchy

Assembly

An assembly is a collection of types and resources that are built to work together and form a logical unit of
functionality. It is an Output Unit, that is .exe or .dll file. It is a unit of Deployment and a unit of versioning and
also it contain MSIL (Microsoft Intermediate Language) code. Assemblies are self describing, it contains all
the metadata about the modules, types, and other elements in the form of a manifest.
Assemblies are of two types: Private and Shared Assemblies.

Private Assemblies

Private assembly is intended only for one application. The files of that assembly must be placed in the same
folder of the application.

Shared Assemblies

Shared assembly is to be made into a Shared Assembly, then the naming conventions are very strict since it
has to be unique across the entire system

Q. Diff. Between Hash table And List

Ans:- List - An array list that supports generic types and enforces type-safety. Since it is non-contiguous, it
can grow in size without re-allocating memory for the entire list. This is the more commonly used list
collection.

Hash table - A Hashtable is a collection of key/value pairs that are arranged based on the hash code of the
key. Or in other words, a Hashtable 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

List can hold duplicate objects

Hashtable is basically a List with no possibility of duplicates (and better performance in some scenarios)

Que . What is the Difference Between IS and AS keyword in C#

Ans.
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.
● The is operator is of boolean type whereas as operator is not of boolean type.
● 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.
● 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.
● The is operator is used for only reference, boxing, and unboxing conversions whereas as
operator is used only for nullable, reference and boxing conversions

Que. What is Page Load Sequence In Master Page And Is Child Pages?

Ans. 1.) Content page Load event.


2) Master page Load event.
3) User Control Page Load Event

Que. Which Version Of C# Language is Used in VS 2010 Or 12

Ans VS 2010 - -------- v4.0


VS 2012 ----------- v5.0

Que. What Are Constraints of SQL ?

Ans SQL constraints are used to specify rules for the data in a table.

Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the
data in the table. If there is any violation between the constraint and the data action, the action is aborted.

Constraints can be column level or table level. Column level constraints apply to a column, and table level constraints
apply to the whole table.

The following constraints are commonly used in SQL:

● NOT NULL - Ensures that a column cannot have a NULL value


● UNIQUE - Ensures that all values in a column are different
● PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
● FOREIGN KEY - Uniquely identifies a row/record in another table
● CHECK - Ensures that all values in a column satisfies a specific condition
● DEFAULT - Sets a default value for a column when no value is specified
● INDEX - Used to create and retrieve data from the database very quickly

Que. What is Cursor in SQL ?


Ans :- A cursor is a temporary work area created in system memory when a SQL statement is executed. A cursor is a
set of rows together with a pointer that identifies a current row. It is a database object to retrieve data from a result set
one row at a time. It is useful when we want to manipulate the record of a table in a singleton method, in other words
one row at a time. In other words, a cursor can hold more than one row, but can process only one row at a time. The
set of rows the cursor holds is called the active set.

Each cursor contains the followings 5 parts,

1. Declare Cursor: In this part we declare variables and return a set of values.
2. Open: This is the entering part of the cursor.
3. Fetch: Used to retrieve the data row by row from a cursor.
4. Close: This is an exit part of the cursor and used to close a cursor.
5. Deallocate: In this part we delete the cursor definition and release all the system resources associated with the
cursor.

Que. Which Are Aggregate and Scalar Function in SQL ?

Ans sql scalar functions: SQL scalar functions return value, based on the input value.

● UCASE() - Converts a field to upper case


● LCASE() - Converts a field to lower case
● MID() - Extract characters from a text field
● LEN() - Returns the length of a text field
● ROUND() - Rounds a numeric field to the number of decimals specified
● NOW() - Returns the current system date and time
● FORMAT() - Formats how a field is to be displayed

sql aggregate functions:SQL aggregate functions return a single value, calculated from
values in a column.

Useful aggregate functions:

● AVG() - Returns the average value


● COUNT() - Returns the number of rows
● FIRST() - Returns the first value
● LAST() - Returns the last value
● MAX() - Returns the largest value
● MIN() - Returns the smallest value
● SUM() - Returns the sum

Que. What is the Difference Between Constants and Read Only C# ?

Ans
1) Const is nothing but "constant", a variable of which the value is constant but at compile time. And it's
mandatory to assign a value to it. By default a const is static and we cannot change the value of a const
variable throughout the entire program.

2 Readonly is the keyword whose value we can change during runtime or we can assign it at run time but
only through the non-static constructor. Not even a method.

Que. What is the Difference Between .TOSTRING() and CONVERTTOSTRING()


Ans - Here both the methods are used to convert the string but the basic difference between them is: "Convert"
function handles NULLS, while "i.ToString()" does not it will throw a NULL reference exception error. So as good
coding practice using "convert" is always safe.

Que:- What Is collection in c#?

Ans:- 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#.

Que:-Types Of index in sql ?

Clustered Indexes:

1.The clustered indexes are indexes which are physically stored in order means it stores in ascending or
descending order in Database.

2.Clustered indexes are created one for each table.

3.When primary key is created then clustered index has been automatically created in the table.

4.If table is under heavy data modifications the clustered indexes are preferable to use.

Non Clustered Indexes:


1.The clustered indexes are used for searching purpose as we can create clustered indexes where primary is is
defined.But Non clustered indexes are indexes which will be created on the multiple joining conditions,multiple
filters used in query.

2.We can create 0 to 249 non-clustered indexes on single table.

3.Foreign keys should be non clustered.When user wants to retrieve heavy data from fields other than primary
key the non clustered indexes are useful.

Que. Can Function Return Multiple Value?

Ans: Generally SQL Server functions will return only one parameter value if we want to return multiple values
from function then we need to send multiple values in table format by using table valued functions.

CREATE FUNCTION testmultiplevalues

@UserId INT

returns table as

return

Select * from UserInformation WHERE UserId=@userId

We can call this function in our query like as shown below

SELECT * FROM dbo.testmultiplevalues(14)

Qu. What is TEmp Table in SQL? What are its Uses?


Ans: A temporary table in SQL Server, as the name suggests, is a database table that exists on the database server
temporarily. It stores a subset of the normal table data for a certain period of time.
Temporary tables are particularly useful when you have a large number of records in a table and need to interact
with small subsets of those records constantly. In such cases, instead of filtering the data again and again to fetch
the subset, you can filter the data once, and store it in a temporary table. Then, you can execute queries on that
temporary table.

Temporary tables are stored inside “tempdb,” which is a system database. Now, let’s take a look at how you can
use temporary data in a simple scenario.

Creating a Temporary Table using SELECT INTO statement


The simplest way of creating a temporary table is by using an INTO statement within a SELECT query.

Let’s create a temporary table that contains the name, age, and gender of all male students’ records from the
student table.

USE schooldb;

SELECT name, age, gender


INTO #MaleStudents
FROM student
WHERE gender = 'Male'

Take a look at the above query. We created a temporary table “#MaleStudents,” which stores names, ages, and
genders of all male students’ records from the student table. To define a temporary table, we use the INTO
statement after the SELECT statement. The name of a temporary table must start with a hash (#).

What Is Difference Between For Loop and Cursor in SQL ?

Ans : Definition:

FOR LOOP allows you to execute code repeatedly for a fixed number of times.

Syntax:

1. FOR loop_counter IN [REVERSE] lowest_number..highest_number


2. LOOP
3. {...statements...}
4. END LOOP;
You would use a CURSOR FOR LOOP when you want to fetch and process every record in a cursor. The CURSOR
FOR LOOP will terminate when all of the records in the cursor have been fetched.

Syntax:

1. FOR record_index in cursor_name


2. LOOP
3. {...statements...}
4. END LOOP;

Difference:

FOR loop will execute code repeatedly as mintioned fixed number of times

CURSOR FOR LOOP will fetch and process/execute the code till end of the cursor data.

Que. How to know which latest record is Inserted in table?

Ans : SELECT @@IDENTITY

● It is used to give the last identity value generated by the statement.


● If the statement did not affect any tables with identity columns, this command returns
NULL
● If the table contains multiple rows generating multiple identity values, @@IDENTITY
returns the last identity value generated.
● Though @@IDENTITY is limited to current session, it is not limited to current scope.
Even if trigger on the table caused identity to be created, you will get identity that was
last created, even if it is a trigger.

Que. Can Constructor be Overloaded ?

Constructors can be overloaded in a similar way as function overloading.

Overloaded constructors have the same name (name of the class) but the different number of
arguments. Depending upon the number and type of arguments passed, the corresponding
constructor is called.

You might also like