Pages

Tuesday 27 August 2013

Common regular expression in ASP .Net

Regular expression for mobile number should be start from 7 or 8 or 9
regular expression that should accept Indian mobile numbers. for example...
9788812345
9876512345
7891234567
8122212345
Syntax :
[789][0-9]{9}
Prefixing an optional (+91|0)? could make it more usable.

Regular expression for email , should be taking only numeric domain name like:

abc133@jhjh.dfsd : True
456@jhj.hh : True
8678@656.687 : False
hgh@679.vhhv : False
hgh@jbnj.656 : False

Syntax :
"^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-a-zA-Z]+[.])+[a-zA-Z]{2,6}$"

Wednesday 21 August 2013

One-liner if statements, how to convert this if-else-statement

Syntax :
return (expression) ? value1 : value2;
If value1 and value2 are actually true and false like in your example, you may as well just

return expression;
or
<result> = <condition> ? <true result> : <false result>;
Example :
string result = 5 > 10 ? "5 is greater than 10." : "5 is not greater than 10.";

Tuesday 16 July 2013

Auto generated Try, Catch and Finally block in C#

Auto generated Try and Finally
tryf  -> press tab
                    try
                    {

                    }
                    finally
                    {


                    }


Auto generated Try and Catch
tryc ->press tab ->press tab 

                     try
                    {

                    }
                    catch (Exception)
                    {
                        
                        throw;

                    }

Friday 29 March 2013

How to create duplicate table with new name in SQL Server 2008


How to create duplicate table with new name in SQL Server 2008

or How to copy or backup table

SELECT *
INTO new_table_name 
FROM old_tablename
Or we can select only the columns we want into the new table:
SELECT column_name(s)
INTO new_table_name 
FROM old_tablename
Example :
SELECT *
INTO Employee_Backup
FROM Employee
only columns:
SELECT LastName,FirstName
INTO Employee_Backup
FROM Employee

Thursday 14 March 2013

Disable your back button


Code to disable your back button on logout page after logging out from page:

Place this code just above the head section of your master page source code(which contains your logout button) and/or also on a page wherever your logout button is placed.

<script type = "text/javascript" >
function disableBackButton() {
window.history.forward();
}
setTimeout("disableBackButton()", 0);
</script>

Find Nth Highest Salary of Employee



The following solution is for getting 6th highest salary from Employee table ,

SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP 6 salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary

You can change and use it for getting nth highest salary from Employee table as follows

SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP n salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary
where n > 1 (n is always greater than one)

Wednesday 6 March 2013

SQL Server Basics of Cursors

Cursor is a database objects to retrieve data from a result set one row at a time, instead of the T-SQL commands that operate on all the rows in the result set at one time.
We use cursor when we need to update records in a database table in singleton fashion means row by row.
Life Cycle of Cursor:
Declare Cursor:
Syntax:
DECLARE cursor_name CURSOR
FOR select_statement --define SQL Select statement
FOR UPDATE [col1,col2,...coln] --define columns that need to be updated
Open Cursor:
Syntax:
OPEN [GLOBAL] cursor_name --by default it is local
Fetch Cursor:
Syntax:
INTO @Variable_name[1,2,..n]
Close Cursor
Syntax:
CLOSE cursor_name --after closing it can be reopen
Deallocate Cursor
Syntax:
DEALLOCATE cursor_name --after deallocation it can't be reopen

An Example of Cursor:

create PROCEDURE sp_rohit
AS  
BEGIN
declare @empCode as varchar(30)
declare @emp_name as varchar(100)

--start cursor for check employee
DECLARE rohit_cursor cursor
for select empcode, emp_name from master_employee

OPEN rohit_cursor
/* first fetch starts the process */
FETCH rohit_cursor  INTO @empCode ,@emp_name
WHILE @@fetch_status = 0 /* while there's still records to process */
BEGIN
                        print @emp_name 
                        FETCH rohit_cursor  INTO @empCode ,@emp_name
                        end
close rohit_cursor
DEALLOCATE rohit_cursor
--end this cursor
end --end store procedure


Tuesday 26 February 2013

SQL Server - Indexes


Relational databases like SQL Server use indexes to find data quickly when a query is processed. 
Creating and removing indexes from a database schema will rarely result in changes to an application's code; indexes operate 'behind the scenes' in support of the database engine. 
The SQL Server engine uses an index in much the same way a reader uses a book index. For example, one way to find all references to INSERT statements in a SQL book would be to begin on page one and scan each page of the book.
 We could mark each time we find the word INSERT until we reach the end of the book. This approach is pretty time consuming and laborious.
 Alternately, we can also use the index in the back of the book to find a page number for each occurrence of the INSERT statements. This approach produces the same results as above, but with tremendous savings in time.

Syntax:
CREATE INDEX [IDX_UnitPrice] ON Products (UnitPrice)
To verify that the index is created, use the following stored procedure to see a list of all indexes on the Products table:
EXEC sp_helpindex Customers 

How It Works
The database takes the columns specified in a CREATE INDEX command and sorts the values into a special data structure known as a B-tree. A B-tree structure supports fast searches with a minimum amount of disk reads, allowing the database engine to quickly find the starting and stopping points for the query we are using.

Advantage of Indexes:

Searching For Records
The most obvious use for an index is in finding a record or set of records matching a WHERE clause. Indexes can aid queries looking for values inside of a range (as we demonstrated earlier), as well as queries looking for a specific value. By way of example, the following queries can all benefit from an index on UnitPrice:
DELETE FROM Products WHERE UnitPrice = 1 
UPDATE Products SET Discontinued = 1 WHERE UnitPrice > 15 
SELECT * FROM PRODUCTS WHERE UnitPrice BETWEEN 14 AND 16 
Indexes work just as well when searching for a record in DELETE and UPDATE commands as they do for SELECT statements.

Sorting Records
SELECT * FROM Products ORDER BY UnitPrice ASC 

Grouping Records
SELECT Count(*), UnitPrice FROM Products GROUP BY UnitPrice

Maintaining a Unique Column
CREATE UNIQUE INDEX IDX_ProductName On Products (ProductName)

Index Drawbacks

  1. Indexes are stored on the disk, and the amount of space required will depend on the size of the table,
  2. Another downside to using an index is the performance implication on data modification statements. Any time a query modifies the data in a table (INSERT, UPDATE, or DELETE), the database needs to update all of the indexes where data has changed.



Type of Indexes in SQL Server - Clustered Indexes & Nonclustered Indexes


Type of Indexes
Clustered Indexes

  1. A common analogy for a clustered index is a phone book. A phone book still sorts entries into alphabetical order. 
  2. The difference is, once we find a name in a phone book, we have immediate access to the rest of the data for the name, such as the phone number and address.
  3. For a clustered index, the database will sort the table's records according to the column (or columns) specified by the index. 
  4. A clustered index contains all of the data for a table in the index, sorted by the index key, just like a phone book is sorted by name and contains all of the information for the person inline. 

create a clustered index:
CREATE CLUSTERED INDEX IDX_SupplierID ON Products(SupplierID) 

  • we can only have one clustered index per table,
  •  In SQL Server, creating a primary key constraint will automatically create a clustered index (if none exists) using the primary key column as the index key.


Non-Clustered Indexes

  1. A book index stores words in order with a reference to the page numbers where the word is located. 
  2. This type of index for a database is a nonclustered index; only the index key and a reference are stored.
  3. The nonclustered indexes created earlier in the chapter contain only the index key and a reference to find the data, which is more like a book index. 

A Disadvantage to Clustered Indexes

  1. If we update a record and change the value of an indexed column in a clustered index, the database might need to move the entire row into a new position to keep the rows in sorted order. This behavior essentially turns an update query into a DELETE followed by an INSERT, with an obvious decrease in performance.
  2.  A table's clustered index can often be found on the primary key or a foreign key column, because key values generally do not change once a record is inserted into the database.

User Defined Functions (UDFs) in SQL Server

User Defined Functions (UDFs)

User defined functions are routines that encapsulates SQL logic inside it. Like stored procedures User defined functions can also be passed input parameters but user defined functions are compiled and executed at runtime so pretty slower than stored procedures.

Certain limitations for User defined functions:

i)  UDF can’t perform DML (data manipulation language) operations like Insertion, Update and Deletion on the base table.

ii) UDF can’t return non deterministic values like GETDATE () etc.

iii) Stored procedure can’t be called from inside a UDF whereas a stored procedure can call a user defined function or another stored procedure inside it.

Syntax:
CREATE FUNCTION dbo.Function
     (
     /*
     @parameter1 datatype = default value,
     @parameter2 datatype
     */
     )
  RETURNS /* datatype */
  AS
     BEGIN
      /* sql statement ... */
     RETURN /* value */
     END
 
Type of UDF :
1) Scalar Functions   (returns a single value)
CREATE FUNCTION EmployeeContactID(@Empid int)
RETURNS int
AS
BEGIN 
Declare @returnvalue int
Select @returnvalue=Employee.ContactID from Employee where Employee.EmployeeID=@Empid
        RETURN   @returnvalue
END
 
Execution:
select dbo.EmployeeContactID(1)
 
2) Inline Functions   (returns a table)
CREATE FUNCTION dbo.GetEmployeeFunction(@empid int)
RETURNS TABLE
AS
RETURN SELECT *
FROM employee where employee.EmployeeID=@empid
 
Execution:
 
select * from dbo.GetEmployeeFunction(1)

Difference between Stored procedures and User defined functions:

i)A stored procedure is pre compiled while a User defined function is compiled and executed at runtime.

ii)A Stored procedure is more flexible than user defined function like you can write complex logic (for example exceptional handling using try catch block is possible in stored procedures which is not possible in user defined functions)

iii) A stored procedure can call another stored procedure or user defined function inside it but a user defined function can’t call stored procedure inside it.

iv)A stored procedure can return non deterministic values but a user defined function can’t return a non deterministic values like Get Date () function.

v) A user defined functions does not support DML operations like insertion, deletion and update on the base table but it is possible via stored procedure.

vi) A user defined function is easier to execute and can be used  inside selection and even for joins but stored procedure can’t be used inside selection queries and it can’t be used to join with other tables.

 

Thursday 21 February 2013

'CASE' in SQL Server


where IsActive =column name
systempostalcode=table name


column IsActive has 1 or 0 values.
we want to return true if IsActive =1, and return false if IsActive =0

select  City, StateCode,  CountryCode, case when IsActive = 1 then 'True' else 'False' end as IsActive   from systempostalcode


Tuesday 19 February 2013

Triggers -- Sql Server


Triggers -- Sql Server

What is a Trigger

  1. A trigger is a special kind of a store procedure that executes in response to certain action on the table like insertion, deletion or updation of data.
  2.  It is a database object which is bound to a table and is executed automatically.
  3.  You can’t explicitly invoke triggers. 
  4. The only way to do this is by performing the required action no the table that they are assigned to.

Types Of Triggers

There are three action query types that you use in SQL which are INSERT, UPDATE and DELETE. So, there are three types of triggers and hybrids that come from mixing and matching the events and timings that fire them.

Basically, triggers are classified into two main types:- 

(i) After Triggers (For Triggers) 
(ii) Instead Of Triggers 

(i) After Triggers

These triggers run after an insert, update or delete on a table. They are not supported for views. 
AFTER TRIGGERS can be classified further into three types as: 

(a) AFTER INSERT Trigger. 
(b) AFTER UPDATE Trigger. 
(c) AFTER DELETE Trigger. 

(a) AFTRE INSERT Trigger

CREATE TABLE Employee_Test
(
Emp_ID INT Identity,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)

INSERT INTO Employee_Test VALUES ('Anees',1000);
INSERT INTO Employee_Test VALUES ('Rick',1200);
INSERT INTO Employee_Test VALUES ('John',1100);
INSERT INTO Employee_Test VALUES ('Stephen',1300);
INSERT INTO Employee_Test VALUES ('Maria',1400);

CREATE TABLE Employee_Test_Audit
(
Emp_ID int,
Emp_name varchar(100),
Emp_Sal decimal (10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
)
This trigger is fired after an INSERT on the table. Let’s create the trigger as:-
CREATE TRIGGER trgAfterInsert ON [dbo].[Employee_Test] 
FOR INSERT
AS
 declare @empid int;
 declare @empname varchar(100);
 declare @empsal decimal(10,2);
 declare @audit_action varchar(100);

 select @empid=i.Emp_ID from inserted i; 
 select @empname=i.Emp_Name from inserted i; 
 select @empsal=i.Emp_Sal from inserted i; 
 set @audit_action='Inserted Record -- After Insert Trigger.';

 insert into Employee_Test_Audit
           (Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
 values(@empid,@empname,@empsal,@audit_action,getdate());

 PRINT 'AFTER INSERT trigger fired.'
GO

To see the newly created trigger in action, lets insert a row into the main table as : 
insert into Employee_Test values('Chris',1500); 

Concept of View in SQL Server


Concept of View in SQL Server

  1. A view is defined by a query and only shows the data which is defined at the time of creation of the view.
  2.  A view is virtual, the data from a view is not stored physically. 
  3. It is a set of queries that, when applied to one or more tables, is stored in the database as an object.
  4. Views are used for security purpose in the database because it hides the name of the table and logic and provides the virtual table.
  5. A view is used to store the SELECT statement only. In the view we can modify the data and table. 

Syntax of a View

CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

Example

create view stud
as  select studname,studid,studaddress
from student where depno='d001'

SQL SERVER – Introduction to JOINs – Basic of JOINs

INNER JOIN

This join returns rows when there is at least one match in both the tables.




SELECT t1.*,t2.*
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.ID = t2.ID

SQL SERVER – Introduction to JOINs – Basic of JOINs

LEFT OUTER JOIN

This join returns all the rows from the left table in conjunction with the matching rows from the right table. If there are no columns matching in the right table, it returns NULL values.


SELECT t1.*,t2.*
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.ID = t2.ID

SQL SERVER – Introduction to JOINs – Basic of JOINs

RIGHT OUTER JOIN

This join returns all the rows from the right table in conjunction with the matching rows from the left table. If there are no columns matching in the left table, it returns NULL values.



SELECT t1.*,t2.*
FROM Table1 t1
RIGHT JOIN Table2 t2 ON t1.ID = t2.ID
WHERE t1.ID IS NULL

SQL SERVER – Introduction to JOINs – Basic of JOINs

CROSS JOIN

This join is a Cartesian join that does not necessitate any condition to join. The resultset contains records that are multiplication of record number from both the tables.


SELECT t1.*,t2.*
FROM Table1 t1
CROSS JOIN Table2 t2



Sunday 17 February 2013

How can find out all Store Procedure in your database by query?


select * from  sysobjects where xtype='P'


How can find out all modify Store Procedure in your database by query?


SELECT name,modify_date,*

FROM sys.objects

WHERE type = 'P'

AND DATEDIFF(D,modify_date, GETDATE()) < 1


How can find out all function in your database by query?


select * from  sysobjects where xtype in ('FN','IF','TF')

Convert Date-Time format in SQL Server


Convert Date-Time format in SQL Server

SELECT CONVERT(VARCHAR(20), GETDATE(), 100)
Feb 18 2013 11:29AM (Mon DD YYYY HH:MM AM/PM)
SELECT CONVERT(VARCHAR(20), GETDATE(), 101)
02/18/2013 (MM/DD/YYYY)
SELECT CONVERT(VARCHAR(20), GETDATE(), 102)
2013.02.18 (YYYY.MM.DD)
SELECT CONVERT(VARCHAR(20), GETDATE(), 103)
18/02/2013 (DD/MM/YYYY)
SELECT CONVERT(VARCHAR(20), GETDATE(), 104)
18.02.2013 (DD.MM.YYYY)
SELECT CONVERT(VARCHAR(20), GETDATE(), 105)
18-02-2013 (DD-MM-YYYY)
SELECT CONVERT(VARCHAR(20), GETDATE(), 106)
18 Feb 2013 (DD Mon YYYY)
SELECT CONVERT(VARCHAR(20), GETDATE(), 107)
Feb 18, 2013 (Mon DD, YYYY)
SELECT CONVERT(VARCHAR(20), GETDATE(), 108)
11:37:14 (HH:MM:SS)
SELECT CONVERT(VARCHAR(20), GETDATE(), 109)
Feb 18 2013 11:37:53 (Mon DD YYYY HH:MM:SS)
SELECT CONVERT(VARCHAR(20), GETDATE(), 110)
02-18-2013 (MM-DD-YYYY)
SELECT CONVERT(VARCHAR(20), GETDATE(), 111)
2013/02/18 (YYYY/MM/DD)
SELECT CONVERT(VARCHAR(20), GETDATE(), 112)
20130218 (YYYYMMDD)
SELECT CONVERT(VARCHAR(20), GETDATE(), 113)
18 Feb 2013 11:40:18 (DD Mon YYYY HH:MM:SS)
SELECT CONVERT(VARCHAR(20), GETDATE(), 114)
11:40:54:040 (HH:MM:SS:MMM)24 hr
SELECT CONVERT(VARCHAR(20), GETDATE(), 120)
2013-02-18 11:53:32 (YYYY-MM-DD HH:MM:SS)

-- we can also use as follow

SELECT SUBSTRING(CONVERT(VARCHAR(10), GETDATE(), 120), 3, 8) AS [YY-MM-DD]
13-02-18 (DD-MM-YYYY)
SELECT REPLACE(CONVERT(VARCHAR(8), GETDATE(), 11), '/', '-') AS [YY-MM-DD]
13-02-18 (DD-MM-YYYY)


Tuesday 12 February 2013

Duplicate Records in SQL Server


see the record without duplicate value

select name,emp_id,City from MyTable

Count Duplicate Records

Syntax:
SELECT YourColumn, COUNT(*) TotalCount
FROM YourTable
GROUP BY YourColumn
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC

Example:
SELECT name, 
 COUNT(email) 
FROM users
GROUP BY email
HAVING ( COUNT(email) > 1 )

Delete Duplicate Records – Rows multipul column


DELETE
FROM MyTable
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM MyTable
GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn3 HAVING COUNT(*)>1))


Delete Duplicate Records – Rows Single column


DELETE
FROM MyTable
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM MyTable
GROUP BY DuplicateColumn HAVING COUNT(*)>1))



Monday 11 February 2013

How to fetch data from Excel file to Data Set in ASP .Net


 protected void Page_Load(object sender, EventArgs e)
    {


        if (!IsPostBack)
        {
            GenerateExcelData();
        }
    }


private void GenerateExcelData()
    {
        try
        {
            OleDbConnection oledbConn;
            string path = System.IO.Path.GetFullPath(@"C:\Users\user\Desktop\PriceAnalysis.xls");
            oledbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
           path + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
         
            oledbConn.Open();
            OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet2$]", oledbConn);
            OleDbDataAdapter oleda = new OleDbDataAdapter();
            oleda.SelectCommand = cmd;
            DataSet ds = new DataSet();
            oleda.Fill(ds, "Table");
            //return ds.Tables[0];
        }
        catch
        {
            //return null;
        }
       

    }
}

Note : where Sheet2 is your sheet name.

Friday 8 February 2013

How can use Split function in C#


I want split 2009-2010 in year format like: 2009

INPUT :   2009-2010  (financialYear)

OUTPUT: 2009


  char[] splitter1 = { '-' };
            string[] year1 = financialYear.Split(splitter1);
            int str1 = Convert.ToInt32(year1[0].ToString());
          
str1 give result: 2009

How to find list of recently execute store procedure



Select DB_Name(dest.[dbid]) As 'databaseName'
   , Object_Name(dest.objectid) As 'procName'
   , Max(deqs.last_execution_time) As 'last_execution'
From sys.dm_exec_query_stats As deqs
Cross Apply sys.dm_exec_sql_text(deqs.sql_handle) As dest

Group By db_name(dest.[dbid])
   , Object_Name(dest.objectid)
Order By databaseName
   , procName
Option (MaxDop 1);


Wednesday 6 February 2013

how to show data in GridView - nice and simple code


 using dataset

add connection string in web config :

<connectionStrings>
<add name="ConnectionString" providerName="System.Data.SqlClient" connectionString="Data Source=USER-PC\SQLEXPRESS;Initial Catalog=master;User id= sa;Password=sa"/>
</connectionStrings>

in .cs page :
string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString(); SqlConnection con = new SqlConnection(str); con.Open(); string s = "select * from employee"; SqlDataAdapter adp = new SqlDataAdapter(s, con); DataSet ds = new DataSet(); adp.Fill(ds, "dataset"); GridView1.DataSource = ds; GridView1.DataBind(); con.Close();

or
SqlConnection con=new SqlConnection(<mention here your connectionstring>);
con.Open();
SqlCommand cmd=new SqlCommand("select * from sam",con);
\\where 'rohit' is table name
SqlDataReader dr=cmd.ExecuteReader();
DataTable dt=new DataTable();
dt.Load(dr);
GridView1.DataSourece=dt;
GridView1.DataBind();
con.Close();


Tuesday 22 January 2013

Interview Questions C# - Part 1


Interview Questions
C# - Part 1
  1. What’s the implicit name of the parameter that gets passed into the class’ set method? Value, and its datatype depends on whatever variable we’re changing.
  2. How do you inherit from a class in C#? Place a colon and then the name of the base class. Notice that it’s double colon in C++.
  3. Does C# support multiple inheritance? No, use interfaces instead.
  4. When you inherit a protected class-level variable, who is it available to? Classes in the same namespace.
  5. Are private class-level variables inherited? Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.
  6. Describe the accessibility modifier protected internal. It’s available to derived classes and classes within the same Assembly (and naturally from the base class it’s declared in).
  7. C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write? Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.
  8. What’s the top .NET class that everything is derived from? System.Object.
  9. How’s method overriding different from overloading? When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.

  1. What does the keyword virtual mean in the method definition? The method can be over-ridden.
  2. Can you declare the override method static while the original method is non-static? No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.
  3. Can you override private virtual methods? No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.
  4. Can you prevent your class from being inherited and becoming a base class for some other classes? Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It’s the same concept as final class in Java.
  5. Can you allow class to be inherited, but prevent the method from being over-ridden? Yes, just leave the class public and make the method sealed.
  6. What’s an abstract class? A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be inherited and have the methods over-ridden. Essentially, it’s a blueprint for a class without any implementation.
  7. When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)? When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.
  8. What’s an interface class? It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes.
  9. Why can’t you specify the accessibility modifier for methods inside the interface? They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it’s public by default.
  10. Can you inherit multiple interfaces?                                                                                         Yes, why not.
  11. And if they have conflicting method names? It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.
  12. What’s the difference between an interface and abstract class? In the interface all methods must be abstract; in the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes.
  13. How can you overload a method? Different parameter data types, different number of parameters, different order of parameters.
  14. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor? Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.
  15. What’s the difference between System.String and System.StringBuilder classes? System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
  16. What’s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.
  17. Can you store multiple data types in System.Array? No.
  18. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? The first one performs a deep copy of the array, the second one is shallow.
  19. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods.
  20. What’s the .NET datatype that allows the retrieval of data by a unique key? HashTable.
  21. What’s class SortedList underneath? A sorted HashTable.
  22. Will finally block get executed if the exception had not occurred? Yes.
  23. What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.
  24. Can multiple catch blocks be executed? No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.
  25. Why is it a bad idea to throw your own exceptions? Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.