Accreditation Bodies
Accreditation Bodies
Accreditation Bodies
Supercharge your career with our Multi-Cloud Engineer Bootcamp
KNOW MOREASP.NET is a web application framework developed to build dynamic web applications, web services, and web APIs. It is part of the .NET framework and allows developers to create powerful, data-driven websites using various programming languages, including C#, VB.NET, and F#. Our expansive set of ASP.NET interview questions is made for both beginners and advanced-level interviewees. The questions are divided widely, covering topics like Routing and URL management, MVC, MVVM, Web Forms, MVC, and Web API programming models, Cookies, Sessions, Cache, and Testing. Our set of ASP.NET interview questions and answers will make you confident to sit and ace the interview.
Filter By
Clear all
2. Server side:
ViewState is a client-side state management mechanism in ASP.NET. It is a default technique used by ASP.NET to persist the value of the page and controls during postbacks.
In ASP.NET ViewState the values are encrypted and stored in a hidden field ( named _VIEWSTATE) on the page as an encoded Base64 string. By default, ViewState is sent to the client browser and then returned to the server in the form of a hidden input control on your page.
Advantages:
Disadvantages:
It's no surprise that this one pops up often in ASP.NET interview questions and answers for freshers.
If the application is storing a lot of data in ViewState, it can affect the overall responsiveness of the page, thereby affecting performance since data is stored on the page itself in hidden controls.
The ideal size of ViewState should be less than 30% of the page size.
DeflateStream and GZipStream are the classes in ASP.NET that provide methods and properties to compress and decompress streams. Using these classes to compress ViewState will reduce its size to around 40%.
It keeps a copy of the response that was sent to the client in memory and subsequent requests are then responded with the cached output until the cache expires, which incredibly improves the ASP.NET web application performance. It is implemented by placing an OutputCache directive at the top of the .aspx page at design time.
Example:
<%@OutputCache Duration="10" VaryByParam= "Id"%>
Sometimes we might want to cache just portions of a page. For example, we might have a header for our page which will have the same content for all users. To specify that a user control should be cached, we use the @OutputCache directive just like we used it for the page.
<%@OutputCache Duration=10 VaryByParam="None" %>
Data Cache is used to store frequently used data in the Cache memory. It's much efficient to retrieve data from the data cache instead of database or other sources. We need use System.Web.Caching namespace. The scope of the data caching is within the application domain unlike "session". Every user can able to access these objects.
This is a frequently asked question in ASP.NET interview questions.
Output cache functionality is achieved using the OutputCache attribute in the ASP.NET page header. Below is the syntax:
<%@ OutputCache Duration="20" Location="Server" Vary By Param="state" Vary By Custom="minor version" Vary By Header="Accept-Language"%>
Cookie is a small piece of information stored on the client machine. This file is located on client machines "C:\Document and Settings\Currently_Login user\Cookie" path. It is used to store user preference information like Username, Password, City and PhoneNo etc. on client machines. We need to import namespace called System.Web.HttpCookie before we use a cookie.
What is the maximum size of a cookie, and how many can be stored in a browser for each web site?
A common question in ASP.NET technical interview questions, don't miss this one.
50 Cookies per domain, with a maximum of 4 KB per cookie (or even 4 KB in total). If you want to support most browsers, then do not exceed 50 cookies per domain and 4093 bytes per domain. That is, the size of all cookies should not exceed 4093 bytes.
Advantages:
Disadvantages:
By using HttpCookie class object. After creating cookie it will be attached to Response Object to send it to the client.
Ex:
HttpCookie cookie1=new HttpCookie ("Username","Ritu"); Response.Cookies.Add (cookie1);
Advantages:
Disadvantages:
ASP NET Core developers are sought after by companies for their niche skill sets. These interview questions on ASP.NET will give you a fair idea of the questions which the interviewer asks during an ASP.NET interview. So, prepare well and good luck!
We can cache multiple response from a single web form by using any one of the attributes from VaryByParam, VaryByHeaders or VaryByCustom attributes.
Example: If we want display different country data on our page where we can choose country name from the drop down list. On SelectedIndexChanged event of the Drop down we have to write some logic to fetch the country data according to the selected value and display the data of the particular country. By setting the VaryByParam attribute to the dropdown will cache all the responses received from server on SelectedIndexChanged event of drop down.
<%@ OutputCache Duration="20" Location="Server" VaryByParam="countryDropDown%> <aspx:DropDownList ID="countryDropDown" AutoPostBack="true" runat="server" onselectedindexchanged=" countryDropDown _SelectedIndexChanged"> <asp:ListItem Text="Germany" Value=" Germany "></asp:ListItem> <asp:ListItem Text="Singapore" Value=" Singapore "></asp:ListItem> <asp: ListItem Text="India" Value=" India "></asp: ListItem> </asp:DropDownList>
A staple in ASP.NET interview questions for advance professionals, be prepared to answer this one.
While programming in C#, we can split the definition of a class over two or more source files. The source files contain a section of the definition of class, and all parts are combined when the application is compiled. For splitting a class definition, we need to use the partial keyword.
Example:
We have a file with a partial class named as Record
namespace HeightWeightInfo { class File1 { } public partial class Record { private int h; private int w; public Record(int h, int w) { this.h = h; this.w = w; } } }
Here is another file named as File2.cs with the same partial class Record
namespace HeightWeightInfo { class File2 { } public partial class Record { public void PrintRecord() { Console.WriteLine("Height:"+ h); Console.WriteLine("Weight:"+ w); } } }
The main method of the project
namespace HeightWeightInfo { class Program { static void Main(string[] args) { Record myRecord = new Record(10, 15); myRecord.PrintRecord(); Console.ReadLine(); } } }
State management basically stores the information of user/Page or object when a user makes a request on a web page, since HTTP is a protocol which doesn’t store the information during each request made by the user.so Asp.net state management is used to preserve the data.
Server Side:-
1) Session: when we want to store the data of web page over multiple requests we use session. In this technique we can store any kind of information or object in server memory it basically stores the information. The session is user specific since it stores the information of user separately. When we store data to Session state, a session cookie named is ASP.NET_SessionId is created automatically.
Example:
Storing the data in Session object
Session ["UserName"] = txtName.Text;
Retrieving the data from the Session object
Label1.Text = Session ["UserName"].ToString();
Session timeout is 20 min if we want to increase the timeout of session then we need to configure the web config
<configuration> <system.web> <sessionState timeout="60" /> </system.web> </configuration>
2). Application object: In application object, we can store the information at the application level rather than User level, where every user can access that information .the main disadvantage is that sometimes there is a concurrency problem, so for that, we use a lock and unlock method. So if multiple requests came for same data then only one thread can do work.
Example:
Application["Message"] = "Hello to all";
We can use an application object to count the number of visitors on that website.
Client Side:
1) Query Strings: When we want to transfer the data over the pages from the URL then we use query string, it cannot handle the huge data and it is compatible with all browsers, we cannot transfer the objects and controls in query strings, so it is not meant for transferring sensitive data through query string.
Example:
Response.Redirect( "SecondPage.aspx?Type=01&Query=Query1" );
Or if we want to use query string to transfer the data then we can encrypt the sensitive data and we can transfer the data.
2). Control State: It is used to transfer the data which is stored in controls .it is just like same as view state but here we can store the data of the controls like dropdown list`s selected items, we cannot disabled the control state if viewstate is disabled then control state works same as view state.
3). View State: It is one of the finest methods to preserve the data, in view state we can store any kind of data like controls data, and even variables and raw data, view state encrypt the data when it will render to the user, so if user wants to see the value of view state in view source it will contain the symbols only which are very hard to decrypt.
The only disadvantage is that page contains much space over the page. To handle the view state we just need to "EnableViewState = true" attribute to any control to save its state,
Example:
public class Person { public string FirstName {get;set;} public string LastName {get;set;} } public partial class default : Web.UI.Pages { Person p = new Person(); p.FirstName = "Harshit"; p.LastName = "Mittal"; ViewState["PersonDetails"]=p; }
4). Cookies: Cookies are used to identify the user on a web page whenever the user makes the request for the first time it stores that request data in the cookies and when the user visit that web page for the second time then browser check the cookies data with second request data made by the user if the result matches browser to consider them as a previous user else consider a new user.
Example: The Case of Remember me on every login page.
There are 2 types of cookies:
Example:
Response.Cookies["nameWithPCookies"].Value = "This is A Persistence Cookie"; Response.Cookies["nameWithPCookies"].Expires = DateTime.Now.AddSeconds(10);
Example:
Response.Cookies["nameWithNPCookies"].Value = "This is A Non Persistence Cookie";
5) Hidden Field - When we want to store the small amount of data or we can say the if want to save the single value, hidden field controls is not rendered on the client browser, it is invisible to the browser.
Example:
<asp:HiddenField ID="HiddenField1" runat="server" />
At the server code
protected void Page_Load(object sender, EventArgs e) { if (HiddenField1.Value != null) { int val= Convert.ToInt32(HiddenField1.Value) + 1; HiddenField1.Value = val.ToString(); Label1.Text = val.ToString(); } }
Hashtable | Dictionary |
---|---|
Hashtable included in System.Collections namespace | Dictionary included in System.Collections.Generic namespace |
It is weakly structured data type in key values pair we can take any object type | In this strong in a data type that you must have to specify the data type of the key value pair |
Returns null as a result if key which does not exist | Throws exception if we try to find with a key that not exists |
It is generic type | It is non-generic type |
It is faster since we don’t need to do boxing and unboxing in this | It is slower than hashtable and it involves an additional step of boxing and unboxing |
Response.Redirect | Server.Transfer |
---|---|
when we want to transfer the information from one page to another page of the same server | when we want to transfer the data to an HTML page of own server or to some other server |
it doesn’t require the query string to preserve the data | It never persists Query Strings and Forms Variables from original request |
It causes additional round trips to the server on each request | It preserves server resources and avoids the unnecessary round trips to the server |
In this, we need to show the URL to the user where we are redirecting | the current URL where the page is redirected is not shown in the browser |
This question is a regular feature in ASP.NET interview questions for senior developer, be ready to tackle it.
As we know we cannot assign the null value to any value type so for that we use nullable type where we can assign null value to the value type variables.
Syntax:
Nullable<T> where T is a type. Nullable type is an instance of System.Nullable<T> struct
Nullable Struct :
[Serializable]
public struct Nullable<T> where T : struct { public bool HasValue { get; } // it will return true if we assigned a value, if there is no value or if we assign a null value it will return false; public T Value { get; } } HasValue : static void Main(string[] args) { Nullable<int> i = null; if (i.HasValue) Console.WriteLine(i.Value); else Console.WriteLine("Null"); }
Example:
[Serializable]
public struct Nullable<T> where T : struct { public bool HasValue { get; } public T Value { get; } } static void Main(string[] args) { Nullable<int> i = null; if (i.HasValue) Console.WriteLine(i.Value); // or Console.WriteLine(i) else Console.WriteLine("Null"); }
Output:
Null
It will check whether an object has been assigned a value if it is having null value it will return false and the else part will be executed.
To get the value of i using the nullable type you have to use GetValueOrDefault() method to get the actual value.
static void Main(string[] args) { Nullable<int> i = null; Console.WriteLine(i.GetValueOrDefault()); }
Extension methods allow you to add our own custom method in any custom class without modifying into it and in our custom class and it will be available throughout the application by specifying namespace only where it is defined.
Example:
namespace ExtensionMethod { public static class IntExtension { public static bool IsGreaterThan(this int i, int value) { return i > value; } } }
Here the first parameter specifies the type on which the extension method is applicable. We are going to use this extension method on int type. So the first parameter must be int preceded with the modifier.
using ExtensionMethod; class Program { static void Main(string[] args) { int i = 10; bool result = i.IsGreaterThan(100); Console.WriteLine(result); } }
Output:
False
In Throw, the original exception stack information is retained.
Example:
For Throw :
try
{ // some operation that can fail } catch (Exception ex) { throw; }
For Throw Ex:
In Throw Ex the original information is overridden by the External information and you will lose the original information.
try { // do some operation that can fail } catch (Exception ex) { // do some local cleanup throw; }
When we use indexers in class it behaves just like the virtual array. The user sets the value of the index and can retrieve the data without pointing an instance or a type member.
using System; class clsIndexer { private string[] val = new string[3]; public string this[int index] { get { return val[index]; } set { val[index] = value; } } } class main { public static void Main() { clsIndexer ic = new clsIndexer(); ic[0] = "C"; ic[1] = "CPP"; ic[2] = "CSHARP"; Console.Write("Printing values stored in objects used as arrays\n"); Console.WriteLine("First value = {0}", ic[0]); Console.WriteLine("Second value = {0}", ic[1]); Console.WriteLine("Third value = {0}", ic[2]); } }
Property | Indexers |
---|---|
we can call any data member of the class directly | internal collection of an object can access its elements by using array notation on the object itself |
class members can be accessed by a simple name | class members can be accessed through an index |
get property doesn`t have parameters | get accessor of an indexer has the same parameter list as with the indexer |
it can be static | it is not static |
It is a powerful tool for determining the contents of unknown assembly which can be used for a wide variety of classes in simple words Reflection provides the ability to determine things and execute code at runtime.
The Namespace used for reflection is System.Reflection.
A ‘rectangular array’ is a multidimensional array where all the rows have the same number of elements, all elements are stored continuously in memory, these are very compact in memory example:
int[] arr = {1,2,4}; int[,] multiArr = new int[2,3];
A ‘jagged array’ is also known as an array of arrays. It is also the multidimensional array one in which the length of the rows need not be the same.
For example,
string[][] jaggedArray = new string[3][]{ new string[] {"TeamCS", "John", "James", "Garry", "Linus"}, new string[] {"TeamMath", "Ramanujan", "Hardy"}, new string[] {"TeamSc", "Albert", "Tesla", "Newton"}, };
The above-jagged array consists of 3 rows, with each row having another array of different size. The elements in the jagged array are a reference of the other arrays, which can be anywhere in the memory
Web API | WCF |
---|---|
It is a web Application Programming Interface | It is a Windows Communication Foundation |
It uses HTTP which is suitable for various protocols which support on various browser | Multiple protocols like: HTTP, HTTPS, Name Pipes, MSMQ, etc., are supported and is allowed to switch between any of them |
Web API a simple class file with .cs (C#) extension | The Extension of WCF service is .svc |
Web API support JSON or XML | It support JSON,XML,ATOM data format |
It is not open source but it can be understood by the client who knows the Xml | If the client knows the XML then it doesn't meant for them |
Expect to come across this popular question in ASP.NET technical interview questions.
Sessions are used in ASP.NET applications for state management. Sessions also make use of cookies to associate sessions with the correct user. But when browser cookies are turned off then in that case cookie-less sessions are used. It appends the values to the browser’s URL that is required to associate with the user.
By default sessions use a cookie in the background, to enable cookie-less sessions, the following settings are required to make in web.config file.
<sessionState cookieless="true" />
The possible options to set cookieless options are:
Advantages of using session:
ViewState is used to persist the data of page or page controls on postback. Viewstates are present on a page as a hidden field with data in an encrypted format. We can store any kind of data.
Advantages:
Disadvantages:
Example:
public class Person { public string FirstName {get;set;} public string LastName {get;set;} } public partial class default : Web.UI.Pages { Person p = new Person(); p.FirstName = "Harshit"; p.LastName = "Mittal"; ViewState["PersonDetails"]=p; }
2. Server side:
ViewState is a client-side state management mechanism in ASP.NET. It is a default technique used by ASP.NET to persist the value of the page and controls during postbacks.
In ASP.NET ViewState the values are encrypted and stored in a hidden field ( named _VIEWSTATE) on the page as an encoded Base64 string. By default, ViewState is sent to the client browser and then returned to the server in the form of a hidden input control on your page.
Advantages:
Disadvantages:
It's no surprise that this one pops up often in ASP.NET interview questions and answers for freshers.
If the application is storing a lot of data in ViewState, it can affect the overall responsiveness of the page, thereby affecting performance since data is stored on the page itself in hidden controls.
The ideal size of ViewState should be less than 30% of the page size.
DeflateStream and GZipStream are the classes in ASP.NET that provide methods and properties to compress and decompress streams. Using these classes to compress ViewState will reduce its size to around 40%.
It keeps a copy of the response that was sent to the client in memory and subsequent requests are then responded with the cached output until the cache expires, which incredibly improves the ASP.NET web application performance. It is implemented by placing an OutputCache directive at the top of the .aspx page at design time.
Example:
<%@OutputCache Duration="10" VaryByParam= "Id"%>
Sometimes we might want to cache just portions of a page. For example, we might have a header for our page which will have the same content for all users. To specify that a user control should be cached, we use the @OutputCache directive just like we used it for the page.
<%@OutputCache Duration=10 VaryByParam="None" %>
Data Cache is used to store frequently used data in the Cache memory. It's much efficient to retrieve data from the data cache instead of database or other sources. We need use System.Web.Caching namespace. The scope of the data caching is within the application domain unlike "session". Every user can able to access these objects.
This is a frequently asked question in ASP.NET interview questions.
Output cache functionality is achieved using the OutputCache attribute in the ASP.NET page header. Below is the syntax:
<%@ OutputCache Duration="20" Location="Server" Vary By Param="state" Vary By Custom="minor version" Vary By Header="Accept-Language"%>
Cookie is a small piece of information stored on the client machine. This file is located on client machines "C:\Document and Settings\Currently_Login user\Cookie" path. It is used to store user preference information like Username, Password, City and PhoneNo etc. on client machines. We need to import namespace called System.Web.HttpCookie before we use a cookie.
What is the maximum size of a cookie, and how many can be stored in a browser for each web site?
A common question in ASP.NET technical interview questions, don't miss this one.
50 Cookies per domain, with a maximum of 4 KB per cookie (or even 4 KB in total). If you want to support most browsers, then do not exceed 50 cookies per domain and 4093 bytes per domain. That is, the size of all cookies should not exceed 4093 bytes.
Advantages:
Disadvantages:
By using HttpCookie class object. After creating cookie it will be attached to Response Object to send it to the client.
Ex:
HttpCookie cookie1=new HttpCookie ("Username","Ritu"); Response.Cookies.Add (cookie1);
Advantages:
Disadvantages:
ASP NET Core developers are sought after by companies for their niche skill sets. These interview questions on ASP.NET will give you a fair idea of the questions which the interviewer asks during an ASP.NET interview. So, prepare well and good luck!
We can cache multiple response from a single web form by using any one of the attributes from VaryByParam, VaryByHeaders or VaryByCustom attributes.
Example: If we want display different country data on our page where we can choose country name from the drop down list. On SelectedIndexChanged event of the Drop down we have to write some logic to fetch the country data according to the selected value and display the data of the particular country. By setting the VaryByParam attribute to the dropdown will cache all the responses received from server on SelectedIndexChanged event of drop down.
<%@ OutputCache Duration="20" Location="Server" VaryByParam="countryDropDown%> <aspx:DropDownList ID="countryDropDown" AutoPostBack="true" runat="server" onselectedindexchanged=" countryDropDown _SelectedIndexChanged"> <asp:ListItem Text="Germany" Value=" Germany "></asp:ListItem> <asp:ListItem Text="Singapore" Value=" Singapore "></asp:ListItem> <asp: ListItem Text="India" Value=" India "></asp: ListItem> </asp:DropDownList>
A staple in ASP.NET interview questions for advance professionals, be prepared to answer this one.
While programming in C#, we can split the definition of a class over two or more source files. The source files contain a section of the definition of class, and all parts are combined when the application is compiled. For splitting a class definition, we need to use the partial keyword.
Example:
We have a file with a partial class named as Record
namespace HeightWeightInfo { class File1 { } public partial class Record { private int h; private int w; public Record(int h, int w) { this.h = h; this.w = w; } } }
Here is another file named as File2.cs with the same partial class Record
namespace HeightWeightInfo { class File2 { } public partial class Record { public void PrintRecord() { Console.WriteLine("Height:"+ h); Console.WriteLine("Weight:"+ w); } } }
The main method of the project
namespace HeightWeightInfo { class Program { static void Main(string[] args) { Record myRecord = new Record(10, 15); myRecord.PrintRecord(); Console.ReadLine(); } } }
State management basically stores the information of user/Page or object when a user makes a request on a web page, since HTTP is a protocol which doesn’t store the information during each request made by the user.so Asp.net state management is used to preserve the data.
Server Side:-
1) Session: when we want to store the data of web page over multiple requests we use session. In this technique we can store any kind of information or object in server memory it basically stores the information. The session is user specific since it stores the information of user separately. When we store data to Session state, a session cookie named is ASP.NET_SessionId is created automatically.
Example:
Storing the data in Session object
Session ["UserName"] = txtName.Text;
Retrieving the data from the Session object
Label1.Text = Session ["UserName"].ToString();
Session timeout is 20 min if we want to increase the timeout of session then we need to configure the web config
<configuration> <system.web> <sessionState timeout="60" /> </system.web> </configuration>
2). Application object: In application object, we can store the information at the application level rather than User level, where every user can access that information .the main disadvantage is that sometimes there is a concurrency problem, so for that, we use a lock and unlock method. So if multiple requests came for same data then only one thread can do work.
Example:
Application["Message"] = "Hello to all";
We can use an application object to count the number of visitors on that website.
Client Side:
1) Query Strings: When we want to transfer the data over the pages from the URL then we use query string, it cannot handle the huge data and it is compatible with all browsers, we cannot transfer the objects and controls in query strings, so it is not meant for transferring sensitive data through query string.
Example:
Response.Redirect( "SecondPage.aspx?Type=01&Query=Query1" );
Or if we want to use query string to transfer the data then we can encrypt the sensitive data and we can transfer the data.
2). Control State: It is used to transfer the data which is stored in controls .it is just like same as view state but here we can store the data of the controls like dropdown list`s selected items, we cannot disabled the control state if viewstate is disabled then control state works same as view state.
3). View State: It is one of the finest methods to preserve the data, in view state we can store any kind of data like controls data, and even variables and raw data, view state encrypt the data when it will render to the user, so if user wants to see the value of view state in view source it will contain the symbols only which are very hard to decrypt.
The only disadvantage is that page contains much space over the page. To handle the view state we just need to "EnableViewState = true" attribute to any control to save its state,
Example:
public class Person { public string FirstName {get;set;} public string LastName {get;set;} } public partial class default : Web.UI.Pages { Person p = new Person(); p.FirstName = "Harshit"; p.LastName = "Mittal"; ViewState["PersonDetails"]=p; }
4). Cookies: Cookies are used to identify the user on a web page whenever the user makes the request for the first time it stores that request data in the cookies and when the user visit that web page for the second time then browser check the cookies data with second request data made by the user if the result matches browser to consider them as a previous user else consider a new user.
Example: The Case of Remember me on every login page.
There are 2 types of cookies:
Example:
Response.Cookies["nameWithPCookies"].Value = "This is A Persistence Cookie"; Response.Cookies["nameWithPCookies"].Expires = DateTime.Now.AddSeconds(10);
Example:
Response.Cookies["nameWithNPCookies"].Value = "This is A Non Persistence Cookie";
5) Hidden Field - When we want to store the small amount of data or we can say the if want to save the single value, hidden field controls is not rendered on the client browser, it is invisible to the browser.
Example:
<asp:HiddenField ID="HiddenField1" runat="server" />
At the server code
protected void Page_Load(object sender, EventArgs e) { if (HiddenField1.Value != null) { int val= Convert.ToInt32(HiddenField1.Value) + 1; HiddenField1.Value = val.ToString(); Label1.Text = val.ToString(); } }
Hashtable | Dictionary |
---|---|
Hashtable included in System.Collections namespace | Dictionary included in System.Collections.Generic namespace |
It is weakly structured data type in key values pair we can take any object type | In this strong in a data type that you must have to specify the data type of the key value pair |
Returns null as a result if key which does not exist | Throws exception if we try to find with a key that not exists |
It is generic type | It is non-generic type |
It is faster since we don’t need to do boxing and unboxing in this | It is slower than hashtable and it involves an additional step of boxing and unboxing |
Response.Redirect | Server.Transfer |
---|---|
when we want to transfer the information from one page to another page of the same server | when we want to transfer the data to an HTML page of own server or to some other server |
it doesn’t require the query string to preserve the data | It never persists Query Strings and Forms Variables from original request |
It causes additional round trips to the server on each request | It preserves server resources and avoids the unnecessary round trips to the server |
In this, we need to show the URL to the user where we are redirecting | the current URL where the page is redirected is not shown in the browser |
This question is a regular feature in ASP.NET interview questions for senior developer, be ready to tackle it.
As we know we cannot assign the null value to any value type so for that we use nullable type where we can assign null value to the value type variables.
Syntax:
Nullable<T> where T is a type. Nullable type is an instance of System.Nullable<T> struct
Nullable Struct :
[Serializable]
public struct Nullable<T> where T : struct { public bool HasValue { get; } // it will return true if we assigned a value, if there is no value or if we assign a null value it will return false; public T Value { get; } } HasValue : static void Main(string[] args) { Nullable<int> i = null; if (i.HasValue) Console.WriteLine(i.Value); else Console.WriteLine("Null"); }
Example:
[Serializable]
public struct Nullable<T> where T : struct { public bool HasValue { get; } public T Value { get; } } static void Main(string[] args) { Nullable<int> i = null; if (i.HasValue) Console.WriteLine(i.Value); // or Console.WriteLine(i) else Console.WriteLine("Null"); }
Output:
Null
It will check whether an object has been assigned a value if it is having null value it will return false and the else part will be executed.
To get the value of i using the nullable type you have to use GetValueOrDefault() method to get the actual value.
static void Main(string[] args) { Nullable<int> i = null; Console.WriteLine(i.GetValueOrDefault()); }
Extension methods allow you to add our own custom method in any custom class without modifying into it and in our custom class and it will be available throughout the application by specifying namespace only where it is defined.
Example:
namespace ExtensionMethod { public static class IntExtension { public static bool IsGreaterThan(this int i, int value) { return i > value; } } }
Here the first parameter specifies the type on which the extension method is applicable. We are going to use this extension method on int type. So the first parameter must be int preceded with the modifier.
using ExtensionMethod; class Program { static void Main(string[] args) { int i = 10; bool result = i.IsGreaterThan(100); Console.WriteLine(result); } }
Output:
False
In Throw, the original exception stack information is retained.
Example:
For Throw :
try
{ // some operation that can fail } catch (Exception ex) { throw; }
For Throw Ex:
In Throw Ex the original information is overridden by the External information and you will lose the original information.
try { // do some operation that can fail } catch (Exception ex) { // do some local cleanup throw; }
When we use indexers in class it behaves just like the virtual array. The user sets the value of the index and can retrieve the data without pointing an instance or a type member.
using System; class clsIndexer { private string[] val = new string[3]; public string this[int index] { get { return val[index]; } set { val[index] = value; } } } class main { public static void Main() { clsIndexer ic = new clsIndexer(); ic[0] = "C"; ic[1] = "CPP"; ic[2] = "CSHARP"; Console.Write("Printing values stored in objects used as arrays\n"); Console.WriteLine("First value = {0}", ic[0]); Console.WriteLine("Second value = {0}", ic[1]); Console.WriteLine("Third value = {0}", ic[2]); } }
Property | Indexers |
---|---|
we can call any data member of the class directly | internal collection of an object can access its elements by using array notation on the object itself |
class members can be accessed by a simple name | class members can be accessed through an index |
get property doesn`t have parameters | get accessor of an indexer has the same parameter list as with the indexer |
it can be static | it is not static |
It is a powerful tool for determining the contents of unknown assembly which can be used for a wide variety of classes in simple words Reflection provides the ability to determine things and execute code at runtime.
The Namespace used for reflection is System.Reflection.
A ‘rectangular array’ is a multidimensional array where all the rows have the same number of elements, all elements are stored continuously in memory, these are very compact in memory example:
int[] arr = {1,2,4}; int[,] multiArr = new int[2,3];
A ‘jagged array’ is also known as an array of arrays. It is also the multidimensional array one in which the length of the rows need not be the same.
For example,
string[][] jaggedArray = new string[3][]{ new string[] {"TeamCS", "John", "James", "Garry", "Linus"}, new string[] {"TeamMath", "Ramanujan", "Hardy"}, new string[] {"TeamSc", "Albert", "Tesla", "Newton"}, };
The above-jagged array consists of 3 rows, with each row having another array of different size. The elements in the jagged array are a reference of the other arrays, which can be anywhere in the memory
Web API | WCF |
---|---|
It is a web Application Programming Interface | It is a Windows Communication Foundation |
It uses HTTP which is suitable for various protocols which support on various browser | Multiple protocols like: HTTP, HTTPS, Name Pipes, MSMQ, etc., are supported and is allowed to switch between any of them |
Web API a simple class file with .cs (C#) extension | The Extension of WCF service is .svc |
Web API support JSON or XML | It support JSON,XML,ATOM data format |
It is not open source but it can be understood by the client who knows the Xml | If the client knows the XML then it doesn't meant for them |
Expect to come across this popular question in ASP.NET technical interview questions.
Sessions are used in ASP.NET applications for state management. Sessions also make use of cookies to associate sessions with the correct user. But when browser cookies are turned off then in that case cookie-less sessions are used. It appends the values to the browser’s URL that is required to associate with the user.
By default sessions use a cookie in the background, to enable cookie-less sessions, the following settings are required to make in web.config file.
<sessionState cookieless="true" />
The possible options to set cookieless options are:
Advantages of using session:
ViewState is used to persist the data of page or page controls on postback. Viewstates are present on a page as a hidden field with data in an encrypted format. We can store any kind of data.
Advantages:
Disadvantages:
Example:
public class Person { public string FirstName {get;set;} public string LastName {get;set;} } public partial class default : Web.UI.Pages { Person p = new Person(); p.FirstName = "Harshit"; p.LastName = "Mittal"; ViewState["PersonDetails"]=p; }
ASP.NET Core is a free and open-source framework that is widely adopted for its easy updates, high-speed performance, and command-line application that allows it to execute, create, and host several applications, easy maintenance, and cross-platform capabilities. It is a framework of the future, and there is a huge demand for professionals in this field. To learn more, you can join the best programming courses with KnowledgeHut to widen your horizons.
Won’t a set of detailed FAQs boost your confidence to crack your ASP.NET interview? We have compiled a few questions and answers on ASP.NET, which will help you to showcase your knowledge to your employer on concepts that lie around it. The following interview questions for ASP.NET will surely help you to prepare and qualify for your ASP Net Core developer role. If you want to develop more knowledge and a firm base regarding ASP.NET, enroll in our Asp-Net Course and build your career's foundation.
Submitted questions and answers are subjecct to review and editing,and may or may not be selected for posting, at the sole discretion of Knowledgehut.
Get a 1:1 Mentorship call with our Career Advisor
By tapping submit, you agree to KnowledgeHut Privacy Policy and Terms & Conditions