SQL Server Interview Day - 4

October 26, 2017 0 Comments A+ a-

1) What is a stored procedure?

A Stored Procedure is a collection or a group of precompiled T-SQL statements are stored together in the database.
It will reduce the network trafic because of the precompilation.

2) Why you use Stored Procedure ?

  • If we use the stored procedure then we will get below advantage.
  • It will reduce the network trafic.
  • It will also reduce the execution time due to precompiled.
  • If will not allow for SQL Injection.
  • Code will stored in server only so indectly We will achieve the security.

3) How can I write a new stored procedure with appropriate example?

Please follow the below example.
CREATE PROCEDURE SP_EmpDetails
AS
BEGIN
SELECT * from tbl_Emp
END

4) What is advantages of using stored procedure in sql server ?

or

What is advantage of function over stored procedure in sql server ?


  • Reuseble the code due to stored in database server.
  • It is very easy to maintain a stored procedure
  • It is preventing the SQL Injection Attacks becasue encrypted code.
  • It is also reduce the execution time and network trafic due to precompiled.

5) How can I pass a parameter to stored procedure in SQL Server ?

Please follow the below example.
CREATE PROCEDURE SP_EmpDetails
@EName VARCHAR(50)
AS
BEGIN
SELECT * from tbl_Emp
WHERE EName = @EName
END

6) How can I excute a stored procedure in SQL Server ?

Please follow the below example.
EXEC SP_EmpDetails 'Tutorials Life'
OR
EXECUTE SP_EmpDetails 'Tutorials Life'

7) How can I pass a output parameter to stored procedure in SQL Server ?

Please follow the below example.
CREATE PROCEDURE SP_EmpDetails
@EName VARCHAR(50),
@EmpCount int Output
AS
BEGIN
SELECT @EmpCount=count(*) from tbl_Emp
WHERE EName = @EName
END

8) How can I excute a stored procedure with output parameter in SQL Server ?

Please follow the below example.
DECLARE @EMPCOUNT int
EXECUTE SP_EmpDetails 'Tutorials Life', @EMPCOUNT
IF(@EMPCOUNT is null)
PRINT '@@EMPCOUNT is null'
ELSE
PRINT @EMPCOUNT

9) What is a sp_depends ?

or

How can I able view the dependencies of the stored procedure ?

Syntax:-
sp_depends SP_Name

  • The above syntax is used to view the dependencies of the stored procedure.
  • It is a system stored procedure.
  • It can able to view the dependencies of other objects like Tables, Views, etc.

10) What is disadvantages/Drawbacks of using stored procedure in sql server ?


  • Limited Coding Functionality such as looping
  • Errors in handling Stored Procedures is poor.
  • maintenance cost is more due to business rules are spread throughout different Stored Procedures.

SQL Server Interview Day - 3

October 23, 2017 0 Comments A+ a-

1) What is constraints in SQL server ?

  • Constraint is rule or restriction imposed and individual column such that unwanted data can't be inserted into tables.
  • We can create constraints on single or multiple columns of any table.
  • Constraints maintain the data integrity and accuracy in the table.
  • Constraints can be column level or table level. Column level constraints apply to a column, and table level constraints apply to the whole table.

2) How many types of constraints in SQL server ?

Constraints are divided into many type. Please follow the below details.

NOT NULL

PRIMARY KEY

FOREIGN KEY

CHECK

DEFAULT

UNIQUE

3) What is NOT NULL constraint ?

It will restricted to NULL value.That means It will not allow the NULL value at record insert/update time.

Example:-
CREATE TABLE tbl_Employee (
ID int NOT NULL,
EmployeeName varchar(200) NOT NULL,
CompanyWebSite varchar(300)
);

Record 1:-
INSERT INTO tbl_Employee (ID, EmployeeName, CompanyWebSite) VALUES ( 1, 'Lipsa','www.tutorialslife.com')
Above record will inserted successfully.

Record 2:-
INSERT INTO tbl_Employee (ID, EmployeeName, CompanyWebSite) VALUES ( 1, NULL,'www.tutorialslife.com')
Above record will not insert into the employee table.

4) What is a PRIMARY KEY ?

  • This is constraint which in forces not null value and no report value in a column using this constraint the record is unique identify.
  • It will not allow to insert/update null value
  • It will also not allow to insert/update duplicate value

Example:-
CREATE TABLE tbl_Employee (
ID int PRIMARY KEY,
EmployeeName varchar(200) NOT NULL,
CompanyWebSite varchar(300)
);

Record 1:-
INSERT INTO tbl_Employee (ID, EmployeeName, CompanyWebSite) VALUES ( 1, 'Lipsa', 'www.tutorialslife.com')
Above record will inserted successfully.

Record 2:-
INSERT INTO tbl_Employee (ID, EmployeeName,CompanyWebSite) VALUES ( 1, 'Sriya', 'www.tutorialslife.com')
Above record will not insert into the employee table because employee ID is duplicate with old value or employee ID "1" already available on the table.

Record 3:-
INSERT INTO tbl_Employee (ID, EmployeeName, CompanyWebSite) VALUES ( NULL, 'Lion', 'www.tutorialslife.com')
Above record will not insert into the employee table because employee ID is NULL value.

5) What is a FOREIGN KEY ?

  • FOREIGN KEY constraints which helpful up to make relationship between two or more than two table using a common attribute.
  • It always refers to same table primary key or another table primary key to make a relationship.
  • It is just opposite of primary key that means it can accept duplicate values and null.
  • It supports the concept of referential integrity.
Example:-
CREATE TABLE tbl_Department (
DepartID int NOT NULL,
DepartName varchar(200),
DepartLoc varchar(300),
);

Record 1:-
INSERT INTO tbl_Department (DepartID, DepartName, DepartLoc) VALUES ( 1, 'Training Department','Bangalore')
Above record will inserted successfully.

Record 2:-
INSERT INTO tbl_Department (DepartID, DepartName, DepartLoc) VALUES ( 2, 'Account Department','New Delhi')
Above record will inserted successfully.

CREATE TABLE tbl_Employee (
ID int PRIMARY KEY,
EmployeeName varchar(200) NOT NULL,
CompanyWebSite varchar(300),
DepartID int,
CONSTRAINT FK_tbl_Employee_tbl_Department FOREIGN KEY (DepartID) REFERENCES tbl_Department(DepartID)
);

Record 1:-
INSERT INTO tbl_Employee (ID,EmployeeName,CompanyWebSite, DepartID) VALUES ( 1, 'Lipsa','www.tutorialslife.com',1)
Above record will inserted successfully.

Record 2:- INSERT INTO tbl_Employee (ID,EmployeeName,CompanyWebSite, DepartID) VALUES ( 1, 'Sriya','www.tutorialslife.com',NULL)
Above record will inserted successfully.

Record 3:-
INSERT INTO tbl_Employee (ID,EmployeeName,CompanyWebSite, DepartID) VALUES ( NULL, 'Lion','www.tutorialslife.com',5)
Above record will not insert into the employee table because Department 5 is not available.

6) What is a CHECK constraint ?

  • CHECK constraint is used for check a condition.
  • CHECK constraint must be specified as a logical expression that evaluated specific condition either TRUE or FALSE.
  • specific condition should be satisfies all values in a column.

Example:-
CREATE TABLE tbl_Employee (
ID int PRIMARY KEY,
EmployeeName varchar(200) NOT NULL,
CompanyWebSite varchar(300),
Age int CHECK (Age>=20)
);

Record 1:-
INSERT INTO tbl_Employee (ID,EmployeeName,CompanyWebSite, Age) VALUES ( 1, 'Lipsa','www.tutorialslife.com', 24)
Above record will inserted successfully.

Record 2:-
INSERT INTO tbl_Employee (ID,EmployeeName,CompanyWebSite, Age) VALUES ( 2, 'Lion','www.tutorialslife.com', 16)
Above record will not insert into the employee table because age value is less then 18.

7) What is a DEFAULT constraint ?

  • The DEFAULT constraint is used to provide a default value for a attribute.
  • When you inserting data does not provide any specific value automatically assign default value only if you specified DEFAULT constraint.
  • DEFAULT constraint only impose at column level.
Example:-
CREATE TABLE tbl_Employee (
ID int PRIMARY KEY,
EmployeeName varchar(200) NOT NULL,
CompanyWebSite varchar(300) DEFAULT 'www.tutorialslife.com'
);

Record 1:-
INSERT INTO tbl_Employee (ID,EmployeeName,CompanyWebSite) VALUES ( 1, 'Lipsa', 'www.tutorialslife.com')
Above record will inserted successfully.

Record 2:-
INSERT INTO tbl_Employee (ID,EmployeeName) VALUES ( 2, 'Lion')
Above record will inserted successfully. It will insert 'www.tutorialslife.com' value for CompanyWebSite column.

8) What is a UNIQUE constraint ?

  • Using this constraint no duplicate value is allow in column but accepts null.
  • It will not allow duplicate value on the column.
  • It will allow null value only one time.
Example:-
CREATE TABLE tbl_Employee (
ID int PRIMARY KEY,
EmployeeName varchar(200) UNIQUE,
CompanyWebSite varchar(300)

);
Record 1:-
INSERT INTO tbl_Employee (ID,EmployeeName,CompanyWebSite) VALUES ( 1, 'Lipsa','www.tutorialslife.com')
Above record will inserted successfully.
Record 2:-
INSERT INTO tbl_Employee (ID,EmployeeName,CompanyWebSite) VALUES ( 2, 'Lipsa','www.tutorialslife.com')
Above record will not insert into the employee table because employee name is duplicate with old value.

Record 3:-
INSERT INTO tbl_Employee (ID,EmployeeName,CompanyWebSite) VALUES ( 3, NULL,'www.tutorialslife.com')
Above record will inserted successfully.

9) What is referential integrity ?

Referential integrity is a concept of relational database, It states that table relationships must between tables in a database remain accurate by applying constraints to prevent users or applications from entering inaccurate data or pointing to data that doesn't exist.

10) What are difference between Table level and Column level constraints?

Table level constraints:-

Table level constraints are those constraints which are imposed end of the column declaration during table deign.
Table level constraints can able to create one or more then one constraint is imposed at one point of time
Table level constraints is syntactically not clear as compare to Column level constraints

Column level constraints:-

Column level constraints are those constraints which are imposed in just after column rectification during table deign.
Column level constraints maximum one constraint is imposed at one point of time
Column level constraints is syntactically more clear.

Please click on this link for more details about constraints.

SQL Server Interview Day - 2

October 21, 2017 0 Comments A+ a-

1) What is the difference between UNION and UNION ALL?

UNION:-

UNION always used for select related information from two tables.
UNION is used to select distinct values from two tables.
UNION selects only unique row from all queries.
UNION is a bit slower as it refines the values to be returned.

UNION All:-

UNION All is used to select all values (i.e. select duplicate records) from the tables.
UNION All selects all rows from all queries.
UNION All is comparatively faster as it just has to present all the values, regardless of clone values.

2) What are the differences between Stored Procedure and the dynamic SQL?

Stored Procedure is a set of statements which is stored in a compiled form.
Dynamic SQL is a set of statements that dynamically constructed at runtime and it will not be stored in a Database and it simply execute during run time.

3) What is the difference between Inner Join and Outer Join?

Inner Join :-

It will retains always common data between two or more then two tables.
If both tables have common records then only it will return the data otherwise null value will be return.
It can applicable for Equi join.

Outer Join :-

It will retains the rows of either table, or both tables.
Outer join will return all the rows whether they are match-based or not matched-based on the join predicate.the variable is dependent on only the first table

Left Outer Join

Right Outer Join

Full Outer Join

4) What is the difference between Left Outer Join and Right Outer Join?

Left Outer Join/Left Join: Return all rows from the left table, and the matched rows from the right table.
Right Outer Join/Right Join: Return all rows from the right table, and the matched rows from the left table.

5) What is the difference between JOIN and UNION?

SQL JOIN allows to retrieve the records on other table based on the given conditions between two tables.
For example:-
Retrieve the employee's reords from emplyee, whose employee are getting more then 10,000 salary.
UNION always used for select related information from two tables.
UNION does not require any condition for joining.
For example:-
SELECT * FROM employee1;
UNION
SELECT * FROM employee2;

6) What is DISTINCT Clause ?

The DISTINCT Clause is used to remove the duplicate records from the dataset and to display only the unique values.
Example:-
Select distinct * from employee1;

7) How data can be copied from one table to another table?

We can achive the result on the below ways.
INSERT INTO SELECT
SELECT INTO

INSERT INTO SELECT:-

Those requires that data types in source and target tables match.
The existing records in the target table are unaffected
Target table is already created.
Emaple:-
Write a query to copy the records from tbl_Emp1 to tbl_emp2 and employee's salary should not be less then 1000?
INSERT INTO tbl_Emp2
SELECT * FROM tbl_Emp1
WHERE salary>=1000;

SELECT INTO:-

The SELECT INTO statement copies data from one table into a new table.
Emaple:-
Write a query create new table "tbl_emp2" and copy the records from tbl_Emp1 whose employee's salary should not be less then 1000 ?
SELECT * INTO tbl_Emp2
FROM tbl_Emp1
WHERE salary>=1000;

8) What is the difference between COMMIT and ROLLBACK?

Every statement between BEGIN and COMMIT becomes persistent to database when the COMMIT is executed.
Every statement between BEGIN and ROOLBACK are reverted to the orginal state when the ROLLBACK was executed.

9) What is Cross Join?

A cross join that does not have a WHERE clause produces the Cartesian product of the tables involved in the join.
The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table.

10) What is a stored procedure?

A Stored Procedure is a collection or a group of precompiled T-SQL statements are stored together in the database.
It will reduce the network trafic because of the precompilation.

What are the types of Normalisation ?

October 19, 2017 0 Comments A+ a-

First Normal Form (1NF) :- 
  • It simplifies each attribute in a relation.
  • In 1NF, there should not be any repeating group of data.
  • Each set of column must have a unique value.
  • It contains atomic values because the table cannot hold multiple values.

Second Normal Form (2NF) :- 

  • In 2NF, the table is required in 1NF.
  • The main rule of 2NF is, 'No non-prime attribute is dependent on the proper subset of any candidate key of the table.'
  • An attribute which is not part of candidate key is known as non-prime attribute.

Third Normal Form (3NF) :- 

  • Third Normal Form (3NF) is used to minimize the transitive redundancy.
  • In 3NF, the table is required in 2NF.
  • While using the 2NF table, there should not be any transitive partial dependency.
  • 3NF reduces the duplication of data and also achieves the data integrity.

BCNF (Boyce – Code Normal Form) :- 

  • BCNF which stands for Boyce – Code Normal From is developed by Raymond F. Boyce and E. F. Codd in 1974.
  • BCNF is a higher version of 3NF.
  • It deals with the certain type of anomaly which is not handled by 3NF.
  • If every determinant is a candidate key, then it is said to be BCNF.
  • Candidate key has the ability to become a primary key. It is a column in a table.

Fourth Normal Form (4NF) :- 

  • Fourth Normal Form (4NF) does not have non-trivial multivalued dependencies other than a candidate key.
  • 4NF builds on the first three normal forms (1NF, 2NF and 3NF) and the BCNF.
  • It does not contain more than one multivalued dependency.
  • This normal form is rarely used outside of academic circles.

Fifth Normal Form (5NF) :- 

  • 5NF is also knows as Project-Join Normal Form (PJ/NF).
  • It is designed for reducing the redundancy in relational databases.
  • 5NF requires semantically related multiple relationships, which are rare.
  • In 5NF, if an attribute is multivalued attribute, then it must be taken out as a separate entity.
  • While performing 5NF, the table must be in 4NF.

SQL Server Interview Day - 1

October 17, 2017 0 Comments A+ a-

1) What is SQL ?

  • SQL stands for Structured Query Language.
  • SQL is used for access the database and manipulate the data/records.
  • SQL is an ANSI (American National Standards Institute) standard. As per ANSI, SQL is the standard language for relational database management systems.

2) What are the two authentication modes in SQL Server?

SQL Server is providing two type authentication modes for access the database.
  • Windows Mode
  • Mixed Mode

.Net Interview Day - 10

October 12, 2017 0 Comments A+ a-

1) What are generics in c#.net?

Generics allow you to delay the specification of the data type of programming elements in a class or a method, until it is actually used in the program.
The classes and the methods can treat the values of different types uniformly with the use if generics.

2)What are advantages of generics in c#.net?

Please follow the below points
  • It facilitate type safety, maximize code reuse and performance.
  • They promote the usage of parameterized types.
  • It can allow to create your own generic classes, delegates, methods, events and interfaces.
  • The CLR compiles and stores information related to the generic types when they are instantiated.

.Net Interview Day - 9

October 12, 2017 0 Comments A+ a-

1) What are the Arrays in C#.Net?

Arrays are using for store similar data types grouping as a single unit. We can access Array elements by its numeric index.
The array indexes start at zero. The default value of numeric array elements are set to zero, and reference elements are set to null .

2) What are the Array Properties in C#.Net?

  • The length cannot be changed once created.
  • Elements are initialized to default values.
  • Arrays are reference types and are instances of System.Array.
  • Their number of dimensions or ranks can be determined by the Rank property.
  • An array length can be determined by the GetLength() method or Length property.

.Net Interview Day - 8

October 12, 2017 0 Comments A+ a-

1) What is a delegate?

  • C# delegates are same as pointers to functions, in C or C++.
  • Delegate is a safe pointer to a method / function. So rather than pointing to the actual function you point to a delegate and via this delegate you can invoke the methods / functions.
  • The reference can be changed at runtime which is hold by an object of delegate.
  • All delegates are implicitly derived from the System.Delegate class.
  • Any method which has the same signature as delegate can be assigned to delegate.

2) What are the uses of delegates in C#?

Below are the list of uses of delegates in C# -
  • Callback Mechanism
  • Asynchronous Processing
  • Abstract and Encapsulate method

3) How do I create delegates in C#?

Step - 1
Declaration
public delegate int MyDelagate(int a, int b);

Step -2
public class Calculate
    {
        public int Add(int a, int b)  //Method 1
        {
            return a + b;
        }
        public int Diff(int a, int b)  //Method 2
        {
            return a - b;
        }
        public int prod(int a, int b)  //Method 3
        {
            return a * b;
        }
        public int div(int a, int b)  //Method 4
        {
            return a / b;
        }
    }

 Step -3 
class Program
    {
        static void Main(string[] args)
        {
            Calculate cal = new Calculate();

            // 1. Instantiation
            MyDelagate Add = new MyDelagate(cal.Add);
            MyDelagate Diff = new MyDelagate(cal.Diff);
            MyDelagate Prod = new MyDelagate(cal.prod);
            MyDelagate Div = new MyDelagate(cal.div);


            // 2.Invocation
            Console.WriteLine("Sum of two integer = {0}", Add(2, 3));
            Console.WriteLine("Difference of two integer = {0}",Diff(5, 2));
            Console.WriteLine("Product of two integer = {0}",Prod(5, 2));
            Console.WriteLine("Division of two integer = {0}", Div(15, 3));
            Console.ReadKey();
        }
    }

output:- 
Sum of two integer = 5 
Difference of two integer = 3 
Product of two integer = 10
 Division of two integer = 5

4) What are the advantages of delegates?


  • Delegates are like C++ function pointers but are type safe.
  • Delegates allow methods to be passed as parameters.
  • Delegates are used in event handling for defining callback methods.
  • Once a delegate is created, the method it is associated will never changes because delegates are immutable in nature.
  • Delegates provide a way to execute methods at run-time.
  • All delegates are implicitly derived from System.MulticastDelegate, class which is inheriting from System.Delegate class.

5) What are different types of Delegates in C#?

Delegates are two type.
  • Single cast delegate
  • Multi cast delegate

6) What is single cast delegate ?

A single cast delegate holds the reference of only single method. Please follow the above example-3.

7) What is multi cast delegate ?

  • A delegate which holds the reference of more than one method is called multi-cast delegate.
  • A multicast delegate only contains the reference of methods which return type is void.

8) How do I create multi cast delegate in C#?

Step - 1
public delegate void MyDelagate(int a, int b);

Step -2
public class Calculate
    {
        public void Add(int a, int b)  //Method 1
        {
            Console.WriteLine("Sum of two integer = {0}", a + b);
        }
        public void Diff(int a, int b)  //Method 2
        {
            Console.WriteLine("Difference of two integer = {0}", a - b);
        }
        public void prod(int a, int b)  //Method 3
        {
            Console.WriteLine("Product of two integer = {0}", a * b);
        }
        public void div(int a, int b)  //Method 4
        {
            Console.WriteLine("Division of two integer = {0}", a / b);
        }
    }

 Step -3 
class Program
    {
        static void Main(string[] args)
        {
            Calculate cal = new Calculate();

            // 1. Instantiation
            MyDelagate multiCastdel = new MyDelagate(cal.Add);
            multiCastdel += new MyDelagate(cal.Diff); // Combine the method using delegate
            multiCastdel += new MyDelagate(cal.prod);
            multiCastdel += new MyDelagate(cal.div);

            // 2.Invocation
            multiCastdel(15, 3);
            Console.ReadKey();
        }
    }
Output:- 
Sum of two integer = 18
Difference of two integer = 12
Product of two integer = 45
Division of two integer = 5 

9) Can we use delegates for asynchronous method calls in C#?

Yes, We can use delegates for asynchronous method calls.

10) What are the different ways of creating a delegate in C# ?

  • Action
  • Func
  • Predicate
  • Lambda
  • Anonymous types

.Net Interview Day - 7

October 12, 2017 0 Comments A+ a-

1) What is this keyword in C# ?

The this keyword refers to the current instance of the class. It can be used to access members from within constructors, instance methods, and instance accessors.
Static constructors and member methods do not have a this pointer because they are not instantiated.
When you are writing code in method or property of a class, using "this" will allow you to make use of the intensiveness.

.Net Interview Day - 6

October 12, 2017 0 Comments A+ a-

1) What is the difference between Dispose and Finalize methods in c#?

Finalize and Dispose both are used for same task like to free unmanaged resources but have some differences.Please follow the below lines.
Finalize:

  • Finalize used to free unmanaged resources those are not in use like files, database connections in application domain and more, held by an object before that object is destroyed. In the Internal process it is called by Garbage Collector and can’t called manual by user code or any service.
  • Finalize belongs to System.Object class.
  • Implement it when you have unmanaged resources in your code, and make sure that these resources are freed when the Garbage collection happens.

Dispose:

  • Dispose is also used to free unmanaged resources those are not in use like files, database connections in Application domain at any time.
  • Dispose explicitly it is called by manual user code.
  • If we need to dispose method so must implement that class by IDisposable interface.
  • It belongs to IDisposable interface.
  • Implement this when you are writing a custom class that will be used by other users.

2) Difference between Equality Operator (==) and Equals() Method in C#?

Both the == Operator and the Equals() method are used to compare two value type data items or reference type data items.
The Equality Operator (==) is the comparison operator and the Equals() method compares the contents of a string.
The == Operator compares the reference identity while the Equals() method compares only contents.
Example:-
static void Main(string[] args)
        {
            int n = 1;
            object num1 = 1;
            object num2 = num1;         
            Console.WriteLine("== operator result is {0}", num1 == num2);
            Console.WriteLine("Equals method result is {0}", num1.Equals(num2));
            Console.WriteLine("\n-----------------------------\n");
            object num3 = n;
            Console.WriteLine("== operator result is {0}", num1 == num3);
            Console.WriteLine("Equals method result is {0}", num1.Equals(num3));
            Console.ReadKey();
        }

3) What is the difference between “as” and “is” operators in C#?

“as” operator is used for casting object to type or class. “is” operator is used for checking the object with type and this will return a Boolean value.

4) What is enum in C#?


  • An enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is used to declare an enumeration. It is a primitive data type, which is user defined.
  • An enum type can be an integer (float, int, byte, double etc.). But if you used beside int it has to be cast.
  • An enum is used to create numeric constants in .NET framework. All the members of enum are of enum type. Their must be a numeric value for each enum type.
  • Enum keyword is used for declaring an enumeration, which consists of named constants and it is called as enumerator lists.
  • Enums are value types in C# and these can’t be inherited. Below is the sample code of using Enums

Eg:-
enum Days { Mon, Tues, Wed, Thus, Fri, Sat};

5. What is the difference between string and StringBuilder in c#?

StringBuilder and string both use to store string value but both have many differences on the bases of instance creation and also for performance:
String:
  • String is immutable. Immutable means once we create string object we cannot modify.
  • Any operation like insert, replace or append happened to change string simply it will discard the old value and it will create new instance in memory to hold the new value.
  • Performance wise string is slow because its’ create a new instance to override or change the previous value.
  • String belongs to System namespace.
StringBuilder:
  • String builder is mutable it means once we create string builder object we can perform any operation like insert, replace or append without creating new instance for every time.
  • Performance wise StringBuilder is very fast because it will use same instance of StringBuilder object to perform any operation like insert value in existing string.
  • StringBuilder belongs to System.Text.Stringbuilder namespace.

6) What is the difference between CType and Directcast in C#?

CType:
  • CType is used for conversion between type and the expression.
  • Ctype is generally used to cast value types.
  • Exceptions are not thrown while using ctype.
  • performance wise, ctype is slow when compared to DirectCast. This is because ctype casting requires execution of runtime helper routines of VB.NET.
Directcast:
  • Directcast is used for converting the object type which requires run time type to be the same as specified type.
  • DirectCast is generally used to cast reference types.
  • When you perform DirectCast on arguments that don't match then it will throw InvalidCastException.
  • Performance of DirectCast is better than ctype. This is because no runtime helper routines of VB.NET are used for casting.

7) What is the difference between "continue" and "break" statements in C#?

Continue:
  • "continue" statement is used to pass the control to next iteration. This statement can be used with – "while", "for", "foreach" loops.
  • using continue statement, you can 'jump over one iteration' and then resume your loop execution.
Break:
  • "break" statement is used to exit the loop.
  • Using break statement, you can 'jump out of a loop'

8) What is the difference between ref and out keywords?

Ref Parameter:
  • The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.
  • If you want to pass a variable as ref parameter you need to initialize it before you pass it as ref parameter to method. Ref keyword will pass parameter as a reference this means when the value of parameter is changed in called method it get reflected in calling method also.
Out Parameter:
  • The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.
  • If you want to pass a variable as out parameter you don’t need to initialize it before you pass it as out parameter to method. Out keyword also will pass parameter as a reference but here out parameter must be initialized in called method before it return value to calling method.

9) What is difference between late binding and early binding in c#?

Polymorphism is an ability to take more than one form of a function means with a same name we can write multiple functions code in a same class or any derived class.
Polymorphism we have 2 different types to achieve that:
  • Compile Time also known as Early Binding or Overloading.
  • Run Time also known as Late Binding or Overriding.
Compile Time Polymorphism or Early Binding:
  • In Compile time polymorphism or Early Binding we will use multiple methods with same name but different type of parameter or may be the number or parameter because of this we can perform different-different tasks with same method name in the same class which is also known as Method overloading.
Run Time Polymorphism or Late Binding:
  • Run time polymorphism also known as late binding, in Run Time polymorphism or Late Binding we can do use same method names with same signatures means same type or same number of parameters but not in same class because compiler doesn’t allowed that at compile time so we can use in derived class that bind at run time when a child class or derived class object will instantiated that’s way we says that Late Binding. For that we have to create my parent class functions as partial and in driver or child class as override functions with override keyword.

10) What is the difference between constant and read only in c#?

Constant:
  • Constant is known as "const" keyword in C# which is also known immutable values which are known at compile time and do not change their values at run time like in any function or constructor for the life of application till the application is running.
  • Constants are static by default.
  • They must have a value at compilation-time
  • Could be declared within functions.
  • These are copied into every assembly that uses them (every assembly gets a local copy of values).
Readonly:
  • Readonly is known as "readonly" keyword in C# which is also known immutable values and are known at compile and run time and do not change their values at run time like in any function for the life of application till the application is running. You can assay their value by constructor when we call constructor with “new” keyword.
  • Must have set value, by the time constructor exits.
  • Are evaluated when instance is created.
  • You can use static modifier for readonly fields.
  • readonly modifier can be used with reference types.
  • read-only modifier can be used only for instance or static fields, you cannot use readonly keyword for variables in the methods.

.Net Interview Day - 5

October 12, 2017 0 Comments A+ a-

1) What is Abstract Class in C#?

Abstract classes, marked by the keyword abstract in the class definition, are typically used to define a base class in the hierarchy. If we don't want a class to be instantiated, define the class as abstract. An abstract class can have abstract and non abstract classes. If a method is defined as abstract, it must be implemented in derived class.

2) What is Sealed Classes in C#?

If a class is defined as Sealed, it cannot be inherited in derived class. That is sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as a sealed class, the class cannot be inherited.
  • Sealed class can be instantiated.
  • It can inherit from other classes.
  • It cannot be inherited.

3) What is static class ?

A static class is very similar to a non-static class, however there's one difference: a static class can’t be instantiated. In different words, you cannot use the new keyword to make a variable of that class type. As a result, there's no instance variable, you access the static class members by using class name.

4) What are the benefits of static class ?

  • It can only have static members.
  • It cannot have instance members as static class instance cannot be created.
  • It is a sealed class.
  • As static class is sealed, so no class can inherit from a static class.
  • We cannot create instance of static class that's the reason we cannot be instance members in static class, as static means shared so one copy of the class is shared to all.
  • Static class also cannot inherit from other classes.

5) Does Abstract class support multiple Inheritance?

No, Abstract class does not support multiple Inheritance.

6) Can abstract class have static methods in C#?

Yes, Abstract class can have static methods in C#.

7) Can abstract class be Sealed in C#?

An abstract class cannot be a sealed class because the sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited.

8) Can we declare abstract methods as private in C# ?

No. Abstract methods can not be private in C#.

9) What is an Interface in C# ?

An interface is similar to a class with method signatures. There wont be any implementation of the methods in an Interface. Classes which implement interface should have an implementation of methods defined in the abstract class. An interface is a specification for a set of class members, not an implementation. An Interface is a reference type and it contains only abstract members such as Events, Methods, Properties etc. It contain only declaration for its members and implementation defined as separate entities from classes. It can't contain constants, data fields, constructors, destructors and static members and all the member declarations inside interface are implicitly public.

10) What is the difference between Interface and Abstract Class?

  • Using Abstract we can not achieve multiple inheritance but using an Interface we can achieve multiple inheritance.
  • An abstract class can have non-abstract methods (concrete methods) while in case of interface all the methods has to be abstract.
  • In an abstract class all data member or functions are private by default while in interface all are public, we can’t change them manually.
  • In an abstract class we need to use abstract keyword to declare abstract methods while in an interface we don’t need to use that.
  • An abstract class use constructor while in an interface we don’t have any type of constructor.
  • An Interface member cannot be defined using the keyword static, virtual, abstract or sealed
  • We can not declare a member field in an Interface.