.Net has five access Specifiers
What is an access specifier?
An access specifier defines the scope of a class member. A class member refers to the variables and functions in a class. A program can have many classes. The programmer gets the privilege to decide the of use access specifier to implement encapsulation and abstraction in C#.
So, when we use Access Specifiers in C# they help the other class members to know how they can access the methods or variables declared/defined inside another class.
C# supports five types of access specifiers to tell the extent of visibility of a class member. They are:-
• public,
• private,
• protected,
• internal and
• protected internal.
Let's now go into detail.
public:
The public access specifier in C# allows a class to expose its member variables and member functions to other functions and objects. So any member declared public can be accessed outside the class also.
Let's check an example for this..
----------------------------------------------------------------
using System;
namespace HelloWorld
{
class hello
{
public int iNum1;
}
class MyMainClass
{
static void Main(string[] args)
{
hello HelloObject=new hello();
HelloObject.iNum1=10; /* since variable iNum1 is public it can be accessed in other classes also*/
Console.WriteLine(HelloObject.iNum1);
}
}
}
----------------------------------------------------------------
private:
The private access specifier in C# is just opposite to the public access specifier. That is it allows a class to hide its member variables and member functions from other class objects and functions. So it is not visible outside the class. By default, the access specifier is private; if public, private or protected is not specified.
Let's check an example for this..
----------------------------------------------------------------
using System;
namespace HelloWorld
{
class hello
{
public int iNum1;
private int iNum2;
public hello()
{
iNum1=0;
iNum2=10;
}
}
class MyMainClass
{
static void Main(string[] args)
{
hello HelloObject=new hello();
//CORRECT METHOD
HelloObject.iNum1=10; //Here since variable iNum1 is public it can be accessed in other classes also
//WRONG METHOD
HelloObject.iNum2=20; /*This line will return an Error since the access to this variable is Private. So it cannot be accessed outside the class*/
Console.WriteLine(HelloObject.iNum1);
}
}
}
----------------------------------------------------------------
protected:
The protected access specifier in C# allows a class to hide its member variables and member functions from other class objects and functions, except the child class. This access specifier is used when we need to use Inheritance in the program.
Let's check an example for this..
----------------------------------------------------------------
using System;
namespace HelloWorld
{
class hello
{
public int iNum1;
protected int iNum2;
}
class world : hello
{
public int AddDetails()
{
iNum1=20;
iNum2=10;
return iNum1+iNum2;
}
}
class MyMainClass
{
static void Main(string[] args)
{
world worldObject=new world();
worldObject.iNum1=50; //Line 1 No Error
worldObject.iNum2=10; //Line 2 Error
Console.WriteLine(worldObject.AddDetails().ToString());
}
}
}
----------------------------------------------------------------
In the above case we have not called the object of the class hello. But we have inherited the class hello to the class world. So all the public and protected members inside the class is accessible inside the derived class also. We don't need to create objects for the base class to access the variables or methods we have in our parent class.
Now inside the Main() function we are assigning value to iNum1 and iNum2. Line 1 will not return any error because the variable iNum1 is public. So, it can be accessed from anywhere in the program, but Line2 will give an Compilation Error saying "iNum2 is inaccessible due to protection level". This is because access of the variable iNum2 is set to protected. The protected members can only be accessed inside the Child class and its parent class.
internal:
Friend & Internal mean the same. Friend is used in VB.NET. Internal is used in C#. Friends can be accessed by all classes within an assembly but not from outside the assembly.
protected internal:
The Protected Friend can be accessed by Members of the Assembly or the inheriting class, and ofcourse, within the class itself.
Lets now understand the above with an example:
----------------------------------------------------------------
using System;
class Student
{
private string sAddress;
protected string sPhNo;
protected internal long iZipCode;
void Hello()
{
Console.WriteLine(“Hello World!”);
}
internal void Hello2()
{
Console.WriteLine(“Hello Student!”);
}
public void SetAddress()
{
Console.WriteLine(“Enter your Address:”)
sAddress = Console.ReadLine();
}
public void SetPhNo()
{
Console.WriteLine(“Enter your Phone Number:”)
sPhNo = Console.ReadLine();
}
public void SetZipCode()
{
Console.WriteLine(“Enter the Zip Code: “);
iZipCode =Convert.ToInt64(Console.ReadLine());
}
public void DisplayStudent()
{
Console.WriteLine(“The Address is: {0}”, sAddress);
}
}
class Display
{
static void Main(string[] args)
{
Student John = new Student();
Console.WriteLine(John.sAddress); //Error: protected members cannot be accessed
John.SetAddress(); //public members can be accessed outside the class definition
John.SetPhNo(); //public members can be accessed outside the class definition
Console.WriteLine(John.sPhNo); //error: protected internal members cannot be accessed outside the class definition
John.SetZipCode(); //public members can be accessed outside the class definition
John.DisplayStudent(); // public members can be accessed outside the class definition
Console.WriteLine(John.sAddress); //error: private members cannot be accessed outside the class definition
John.Hello(); //error: private members cannot be accessed outside the class definition
John.Hello2(); //displays Hello student!
Console.ReadLine();
}
}
What is the difference between primary key and unique key?
Ans:There is not difference between Primary key and unique key except Primary key does not accept null values while unique key accept the null value.
What is boxing and unboxing concepts in .net?
Ans: Boxing is a process of converting value type into reference type
Unboxing is a process of converting reference type to value type.
What are the differences between value type and reference type?
Ans: Value type contain variable and reference type are not containing value directly in its memory.
Memory is allocated in managed heap in reference type and in value type memory allocated in stack. Reference type ex-class value type-struct, enumeration
What is SOA(Service Oriented Architecture)?
A service-oriented architecture is essentially a collection of services. These services communicate with each other. The communication can involve either simple data passing or it could involve two or more services coordinating some activity. Some means of connecting services to each other is needed.
Why we go for page rendering in Asp.Net Page life cycle?
Ans: Browser understands an only html control that’s why in page rendering we will convert the aspx controls into html controls.
Write a sample query for self join?
Ans: Select e1.ename, e2.empid from emp e1, emp e2 where e1.empid=e2.mgrid;
Can we change the index of primary key on table?
Ans: No
How to find out which index is defined on table?
Ans: sp_helpindex tablename
The out Parameter
The out parameter can be used to return the values in the same variable passed as a parameter of the method. Any changes made to the parameter will be reflected in the variable.
public class mathClass
{
public static int TestOut(out int iVal1, out int iVal2)
{
iVal1 = 10;
iVal2 = 20;
return 0;
}
public static void Main()
{
int i, j; // variable need not be initialized
Console.WriteLine(TestOut(out i, out j));
Console.WriteLine(i);
Console.WriteLine(j);
}
}
The ref parameter
The ref keyword on a method parameter causes a method to refer to the same variable that was passed as an input parameter for the same method. If you do any changes to the variable, they will be reflected in the variable.
You can even use ref for more than one method parameters.
namespace TestRefP
{
using System;
public class myClass
{
public static void RefTest(ref int iVal1 )
{
iVal1 += 2;
}
public static void Main()
{
int i; // variable need to be initialized
i = 3;
RefTest(ref i );
Console.WriteLine(i);
}
}
}
ref means that value is already set, method can read it and can modify it.
out means that value isn't set and method must set it before return and couldn't read before setting value.
What is “ref” keyword in C#
“ref Keyword” in C#.
Passing variables by value is the default. However, we can force the value parameter to be passed by reference.
Point to be kept in mind while using ref keyword.
variable “must” be initialized before it is passed into a method.
Example, Without Using ref keyword
class Test
{
public static void Main()
{
int a = 3;
DoWork(a);
Console.WriteLine("The value of a is " + a);
}
public static void DoWork(int i)
{
i++;
}
}
The program will result in : The value of a is 3
Example, With the Use of ref keyword
class Test
{
public static void Main()
{
int a = 3; // must be initialized
DoWork(ref a); // note ref
Console.WriteLine("The value of a is " + a);
}
public static void DoWork(ref int i) // note ref
{
i++;
}
}
The program will result : The value of a is 4
Can you write the program to find the length of string without using library function?
Ans: for (int i=0; str[i]!=”\n”; i++)
{
Count++;
}
What is the difference between scope_identity() and current_identity()?
Ans: Scope_identity and current _identity both are similar and it will return the last identity value generated in the table.
Scope_Identity will return the identity value in table that is currently in scope
What are difference between POST and GET Methods?
POST Method ():
- Data is not appended to the URL.
- Data is Secret
- it is a two call system.
- There is no Limit on the amount of data. That is characters any amount of data can be sent.
- Data transmission is comparatively slow.
- No default and should be explicitly specified.
GET Method ():
- Data is appended to the URL.
- Data is not secret.
- It is a single call system
- Maximum data that can be sent is 256.
- Data transmission is faster
- this is the default method for many browsers
What are difference between truncate and delete?
Ans: 1) Delete keep the lock over each row where Truncate keeps the lock on table not on all the row.
2) Counter of the Identity column is reset in Truncate where it is not reset in Delete.
3) Trigger is not fired in Truncate where as trigger is fired in Delete.
4) In TRUNCATE we cannot rollback.
5) In DELETE we can rollback
• DataTable,DataSet,DataView,Data Adapter,Data Reader
DataGridView is a control which gets data from DataTable, DataView or Dataset.
DataTable is an in-memory table.
DataSet is a collection of DataTable objects.
Difference Between DataSet and DataTable.
A Dataset has an overhead perfomance hit when its loaded with a lot of Data. Now let me be more clearer, a Dataset can Contain a lot of Datatable :) A Dataset is like a Container for Datatables because every dataset has a datatable contained inside it and a Datatable is like a table you have in SQL and a Dataset its like a Database that contain table(Datatable)
DataView:: Represents a customized view of a DataTable for
sorting, filtering, searching, editing, and navigation.
See the following example u can get Better idea...
// Create a new DataTable.
System.Data.DataTable table = new
DataTable("Customers");
// Declare variables for DataColumn and DataRow objects.
DataColumn column;
DataRow row;
// Create new DataColumn, set DataType,
// ColumnName and add to DataTable.
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "ID";
column.ReadOnly = true;
column.Unique = true;
// Add the Column to the DataColumnCollection.
table.Columns.Add(column);
// Create second column.
// Add the column to the table.
table.Columns.Add("FirstName",
System.Type.GetType("System.String"));
// Add the column to the table.
table.Columns.Add("LastName",
System.Type.GetType("System.String"));
// Make the ID column the primary key column.
DataColumn[] PrimaryKeyColumns = new DataColumn[1];
PrimaryKeyColumns[0] = table.Columns["id"];
table.PrimaryKey = PrimaryKeyColumns;
// add new datarow by adding the values
table.Rows.Add("C101", "Rajesh", "Kumar");
table.Rows.Add("C102", "Fareed", "sk");
table.Rows.Add("C103", "Rajesh", "Raji");
//Sort and display
DataView Dview = new DataView(table);
Dview.Sort = "LastName ASC, FirstName ASC";
GridView1.DataSource = Dview;
GridView1.DataBind();
What is the difference Grid View and between Data Grid (Windows)?
Ans:
1) GridView Control Enables you to add sorting, paging and editing capabilities without writing any code.
2)GridView Control Automatically Supports paging by setting the ‘PagerSetting’ Property.The Page Setting Property supports four Modles
a. Numeric(by default)
b. Next Previous
c. NumericFirstLast
d. Next PreviousLast
3)It is Used in asp.net
4)GridView Supports RowUpdating and RowUpdated Events.
5)GidView is Capable of Pre-Operations and Post-Operations.
6)GridView Has EditTemplates for this control
7)It has AutoFormat
DataGrid(Windows)
1)DataGid Control raises single Event for operations
2)DataGird Supports the SortCommand Events that occur when a column is Soted.
3)DataGrid Supports UpdataCommand Event that occurs when the UpdateButton is clicked for an item in the grid.
4)DataGrid is used in Windows GUI Application.
5)It doesnot have EditTemplates for this control
6)It doesnot have AutoFormat
If I write System.exit (0); at the end of the try block, will the finally block still execute?
Ans: No in this case the finally block will not execute because when you say system.exit(0),the control immediately goes out of the program, and thus finally never executes.
What are the different levels of State management in ASP.NET?
Ans:
State management is the process by which you maintain state and page information over multiple requests for the same or different pages.
There are 2 types State Management:
1. Client – Side State Management
This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator (url), or a cookie. The techniques available to store the state information at the client end are listed down below:
a. View State – Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. It is used by the Asp.net page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state.
b. Control State – If you create a custom control that requires view state to work properly, you should use control state to ensure other developers don’t break your control by disabling view state.
c. Hidden fields – Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed.
d. Cookies – Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site.
e. Query Strings - Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL.
2. Server – Side State Management
a. Application State - Application State information is available to all pages, regardless of which user requests a page.
b. Session State – Session State information is available to all pages opened by a user during a single visit.
Both application state and session state information is lost when the application restarts. To persist user data between application restarts, you can store it using profile properties.
• Data Reader and DataAdapter
Data Reader:
If your Data access operations is mainly fetching and displaying the records and doesnt involve insert/update/delete statements and other manipulations (forward only, read only) actions, go for the DataReader.
DataReader offers a forward only read stream of access to the records. It is very useful in cases where we just grab the data from the database to display in DataGrid, Label and other Webcontrols.
However, DataReader requires the connection with the database open until its operation is completed.
Data Reader will read only one record at a time.So memory consumption will be less,it is purely connection oriented it will use connection.
exclusively when datareader is closed.the memory will be released on the server machine and connection will be used for any other purpose.
Data Reader read only forward only
It's connection oriented
should Explicitly close the connection
• Data Adapter
Data Adapter acts as a mediator between dataset and database server. it will read data from the database server and places with in dataset the manipulations on the dataset will be updated with the database server. Data Adapter is disconnected its acts as a bridge between data set and database. Data Adapter is nothing but mediator between Dataset and Database, first data adapter connect to the database then fetches into the data set and closes the connection, you can update the data into dataset, also you can update database as well.
Abstract Class:
Abstract class is a class which can’t be instantiate. Class should have “Abstract” key word with the name. In any one of the method of class having abstract method with in it, then it should be define as abstract class. The class which derived the abstract class should have definition of the abstract method. These classes which derived the abstract class and implement the abstract methods call concrete class.
Abstract class may have the definition of function or may not. Below is the simple example of an abstract class
public abstract alass AbstractStudent
{
String Roll
{
get;
set;
}
String FirstName
{
get;
set;
}
String LastName
{
get;
set;
}
Public String GetStudentDetails()
{
// Implementation of Method
}
public String SaveStudentDetails ()
{
// Implementation of Method
}
public abstract String CalculateWage();
}
So, the class having one abstract method so we need to mention the class as "abstract" .
Difference between Abstract Class and Interface?
Abstract class is a class which can’t be instantiated and which can have methods with definition as well as declaration also. This can be inherited.
As for Example:
public abstract class AbstractStudent
{
String Roll
{
get;
set;
}
String FirstName
{
get;
set;
}
String LastName
{
get;
set;
}
Public String GetStudentDetails()
{
// Implementation of Method
}
public String SaveStudentDetails ()
{
// Implementation of Method
}
public abstract String CalculateWage();
}
Interface can only contain the methods declaration and can be implemented in the class.
As for Example:
Public interface IStudnet
{
String Roll
{
get;
set;
}
String FirstName
{
get;
set;
}
String LastName
{
get;
set;
}
String GetStudentDetails();
String SaveStudentDetails ();
}
• Use Of Global.asax File:
The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level events raised by ASP.NET or by HttpModules. The Global.asax file resides in the root directory of an ASP.NET-based application. At run time, Global.asax is parsed and compiled into a dynamically generated .NET Framework class derived from the HttpApplication base class. The Global.asax file itself is configured so that any direct URL request for it is automatically rejected; external users cannot download or view the code written within it.
Event
• Application_Init: Fired when an application initializes or is first called. It's invoked for all HttpApplication object instances.
• Application_Disposed: Fired just before an application is destroyed. This is the ideal location for cleaning up previously used resources.
• Application_Error: Fired when an unhandled exception is encountered within the application.
• Application_Start: Fired when the first instance of the HttpApplication class is created. It allows you to create objects that are accessible by all HttpApplication instances.
• Application_End: Fired when the last instance of an HttpApplication class is destroyed. It's fired only once during an application's lifetime.
• Application_BeginRequest: Fired when an application request is received. It's the first event fired for a request, which is often a page request (URL) that a user enters.
• Application_EndRequest: The last event fired for an application request.
• Application_PreRequestHandlerExecute: Fired before the ASP.NET page framework begins executing an event handler like a page or Web service.
• Application_PostRequestHandlerExecute: Fired when the ASP.NET page framework is finished executing an event handler.
• Applcation_PreSendRequestHeaders: Fired before the ASP.NET page framework sends HTTP headers to a requesting client (browser).
• Application_PreSendContent: Fired before the ASP.NET page framework sends content to a requesting client (browser).
• Application_AcquireRequestState: Fired when the ASP.NET page framework gets the current state (Session state) related to the current request.
• Application_ReleaseRequestState: Fired when the ASP.NET page framework completes execution of all event handlers. This results in all state modules to save their current state data.
• Application_ResolveRequestCache: Fired when the ASP.NET page framework completes an authorization request. It allows caching modules to serve the request from the cache, thus bypassing handler execution.
• Application_UpdateRequestCache: Fired when the ASP.NET page framework completes handler execution to allow caching modules to store responses to be used to handle subsequent requests.
• Application_AuthenticateRequest: Fired when the security module has established the current user's identity as valid. At this point, the user's credentials have been validated.
• Application_AuthorizeRequest: Fired when the security module has verified that a user can access resources.
• Session_Start: Fired when a new user visits the application Web site.
• Session_End: Fired when a user's session times out, ends, or they leave the application Web site.
what is ExecuteDataset?
Executes the command and returns the results in a new dataset with all the rows.
What is a Partial class?
Ans: Instead of defining an entire class, you can split the definition into multiple classes by using partial class keyword. When the application compiled, c# compiler will group all the partial classes together and treat them as a single class. There are a couple of good reasons to use partial classes. Programmers can work on different parts of classes without needing to share same physical file
Ex:
Public partial class employee
{
Public void somefunction()
{
}
}
Public partial class employee
{
Public void function ()
{
}
}
Difference Between Executescalar and ExecuteNonQuerry
ExecuteScalar - Returns only one value after execution of the query. It returns the first field in the first row. This is very light-weight and is perfect when all your query asks for is one item. This would be excellent for receiving a count of records (Select Count(*)) in an sql statement, or for any query where only one specific field in one column is required.
ExecuteNonQuery - This method returns no data at all. It is used majorly with Inserts and Updates of tables. It is used for execution of DML commands.
Example:
SqlCommand cmd = new SqlCommand("Insert Into t_SomeTable Values('1','2')",con);
//note that con is the connection object
con.Open();
cmd.ExecuteNonQuery(); //The SQL Insert Statement gets executed
Difference between ExecuteNonQuery, ExecuteScalar and ExecuteReader
1)ExecuteNonQuery
a) Used mainly for action queries(insert,delete,update,create,alter,drop).
It can also be used with select queries.
example: A stored procedure in SQL Server that can be used for autogeneration of ID's using its
output parameter can have the value of output parameter returned on a windows form using ExecuteNonQuery.
b)returns an int value indicating the number of affected rows
2)ExecuteScalar
a)Used in queries where we have to read a single value
example: 1)select count(*) from emp
2) select ename from emp where eno=100
b)returns an object
3)ExecuteReader
b)Used in queries where we have to read a complete row of the data
example: select * from emp where eno=100
b)It initializes a SqlDataReader/OleDbDataReader variable which can then
be used to read the data returned.
What is difference between constants, read-only and, static?
Constants: The value can’t be changed
Read-only: The value will be initialized only once from the constructor of the class.
Static: Value can be initialized once.
What is the difference between application exception and system exception?
Ans: The difference between application exception and system exception is that system exceptions are thrown by CLR and application exceptions are thrown by applications.
What is the difference between authorization and authentication?
Ans: Authorization is a process of allowing or denying resources to particular user or record
Declaration of authorization is
Sometimes authorization allows the unauthorized persons at that time we will use
Authentication means
Authentication is a process where we identify the credentials of user i.e. username, password and create an identity to mention user as an authenticated.
How to get the version of the assembly?
Ans: lbltxt.text=Assembly. GetExecutingAssembly().GetName().Version.ToString();
What is the location of Global Assembly Cache on the system?
Ans: c:\Windows\assembly
What is the serialization means?
Ans: Serialization is a process of converting object into a stream of bites.
What is synchronization?
Ans: The mechanism needed to block one thread access to the data. If the data is being accessed by another thread.
Synchronization can be accessed by using system.monitor class
A monitor class methods are enter, exit, pulse for this lock statement is also used
Suppose if we need to synchronize some data at that time we need to place that data in this block
Lock
{
}
Whatever the data has been placed into the lock block that data has been blocked
What are the thread priority levels?
Ans: Thread priority levels are five types
0 - Zero level
1 - Below Normal
2 - Normal
3 - Above Normal
4 - Highest
By Default priority level is 2
What is the difference between .tostring(), Convert.tostring()?
Ans: The basic difference between them is “Convert” function handles NULLS while
“.ToString()” does not it will throw a NULL reference exception error. So as a good coding
practice using “convert” is always safe.
How many web.config files are there in 1 project?
Ans: There might be multiple web.config files for a single project depending on the hierarchy of folders inside the root folder of the project, so for each folder we can use one web.config file
What is the difference between throw and throw ex?
What is the difference between view state and hidden field?
Ans: viewstate is secured hidden field is insecure
Viewstate will store large amount of data but hidden filed will store small amount of data.
What is the Difference between read only and constant variables?
Ans: Read only can assign the values at runtime only.
Constant will assign the values at compile time only.
We cannot modify the both variable values.
What is static keyword in .Net?
Ans: Static is same as constant variable but we can change the value of static variable and we can access the variables without creating any instances