C Sharp Rapid Fire Questions 1


Back to Notes on .NET

C# General Interview Questions

C# Questions on properties, events etc

C# Questions on Properties, Events etc

C# Rapid Fire Questions 1 

C# Rapid Fire Questions 2

SQL Interview Questions 1

SQL Interview Questions 2

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Questions...

1. What is the difference between a Struct and a Class?
Ans.
Structs are value-type variables and are thus saved
on the stack -> additional overhead but faster retrieval. Another difference is that structs CANNOT inherit.  Classes are reference types and structs are value types. Since classes are reference type, a class variable can be assigned null.But we cannot assign null to a struct variable, since structs are value type.

struct AStruct
{  
  int aField;
}

class  AClass
{  
   int aField;
}

class MainClass
{
   public static void Main() 
   {  
       AClass b = null;  // No error.
       AStruct s = null; // Error
/* [ Cannot convert null to 'AStruct' because  it is
a value type ].*/
   }
}

 When you instantiate a class, it will be allocated on the heap.When you instantiate a struct, it gets created on the stack. You will always be dealing with reference to an
object ( instance ) of a class. But you will not be dealing
with references to an instance of a struct ( but dealing directly with them ).

When passing a class to a method, it is passed by
reference. When passing a struct to a method, it's passed
by value instead of as a reference.

You cannot have instance Field initializers in structs.
But  classes can have initializers.

class MyClass
{
  int myVar =10;    //  no syntax error.   
  public void MyFun( )   
  { 
     //  statements   
  }
}

struct MyStruct
{   
  int myVar = 10;  //syntax error
  public void MyFun( )   
  {
        //  statements   
  }
}

Classes can have explicit parameterless constructors.
But structs cannot have explicit parameterless constructors.

class MyClass
{  
  int myVar = 10;  
  public MyClass( ) // no syntax error. 
  { 
     // statements  
  }
}

struct MyStruct
{  
  int myVar;  
  public MyStruct( ) // syntax error.  
  {
       // statements  
  }
}

Classes must be instantiated using the new operator. But structs can be instantiated without using the new operator.

MyClass aClassObj;
/*  MyClass aClassObj=new MyClass(); is the correct
format.aClassObj.myVar=100;//NullReferenceException
(because aClassObj does not contain a reference to an object
of type myClass). */

MyStruct  aStructObj;aStructObj.myVar=100;// no exception.

Classes support inheritance.But there  is no inheritance for structs. ( structs don't support inheritance polymorphism )

(1)
struct MyStruct
{
 int aStructVar; 
 internal void aStructMethod()
 {
   // statements
 }
}

class MyClass : MyStruct   // Syntax error.
{
  int aClassVar; 
  int aClassMethod() 
  {
     // statements
  }
}


(2)
class MyClass
{
  int aClassVar;
  int aClassMethod()
  {
     // statements
  }
}

struct MyStruct : MyClass   // Syntax error.
{
  int aStructVar;
  internal void aStructMethod()
  { 
    // statements 
  }
}

Since struct does not support inheritance, access modifier
of a member of a struct cannot be  protected or protected
internal. It is not mandatory to initialize all Fields inside
the constructor of a class. But all the Fields of a struct 
must be fully initialized inside the constructor.

class MyClass //No error( No matter whether the Field
                   //'MyClass.myString' is initialized or not ).
{  
  int  myInt;  
  string myString;
  public MyClass( int aInt )
  { 
     myInt = aInt;  
  }
}

struct MyStruct // Error ( Field ' MyStruct.myString ' must
            //be fully assigned before it leaves the constructor ).
{
   int myInt;
   string myString;
   public MyStruct( int aInt )
   {      myInt = aInt;
   }
}
 

A class is permitted to declare a destructor.But a struct is not permitted to declare a destructor.

struct MyStruct
{   
  int myInt;
  public MyStruct( )  
  {    }    ~MyStruct( )   //Error.
  {
    Console.WriteLine("Destructor of MyStruct object");
  }
}

class MyClass
{
    int myInt;
    public MyClass( )    {    }    ~MyClass( ) // No Error.
    { 
       Console.WriteLine("Destructor of MyClass object");      }
}

Classes are used for complex and large set data. structs are
simple to use. structs are useful whenever you  need a type that will be used often and is mostly just a piece of data.

 

2. What does the term immutable mean?
Ans.
It means to create a view of data that is not
modifiable and is temporary of data that is
modifiable.
 
Immutable means you can't change the currrent data,
but if you perform some operation on that data, a
new copy is created. The operation doesn't change
the data itself. Like let's say you have a string
object having "hello" value. Now if you say

temp = temp + "new value"

a new object is created, and values is saved in that.
The temp object is immutable, and can't be changed.

An object qualifies as being called immutable if its value
cannot be modified once it has been created. For example,
methods that appear to modify a String actually return a new
String containing the modification.  Developers are
modifying strings all the time in their code.  This may
appear to the developer as mutable - but it is not.  What
actually happens is your string variable/object has been
changed to reference a new string value containing the
results of your new string value.  For this very reason
.NET has the System.Text.StringBuilder class.  If you find
it necessary to modify the actual contents of a string-like object heavily, such as in a for or foreach loop, use the System.Text.StringBuilder class.

3. Can we have private constructor? When can I
use them? When should we implement a private constructor?

Ans. Private constructors would be mainly used for singleton
patterns and for classes that are module-like
(only static/shared methods/attributes)

The idea of the singleton is that you don't have a public
constructor, specifically to prevent people from
instantiating more than one of them. You call a
non-constructor method to return the singleton instance.
If it doesn't exist, the method calls the private
constructor to create it. Then it returns a reference
to the singleton instance.

An example below...

// .NET Singleton
sealed class Singleton
{
 private Singleton() {}
 public static readonly Singleton Instance = new Singleton();
}

Obviously you'd need to add some properties and methods to get something useful, but you get the idea. Watch out for
thread safety issues.

This link may give more insight: ttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpatterns/html/ImpSingletonInCsharp.asp

4.Explain the differences between Server-side and
Client-side code?
Ans.
Server side code will execute at server end
all the business logic will execute at server end
where as client side code will execute at client side
at browser end. Usually, scripts like Javascript,
VBScript & JScript etc. take care of client side
funtions.

5. What type of code (server or client) is found in
a Code-Behind class?
Ans.
Server side.

6.Should validation (Did the user enter a real date?)
occur server-side or client-side? Why?
Ans.
Ideally it should occur client-side.
It saves round-trip to server & thus saves time!!!  It also avoids SQL Injections from malicious users. SQL injection is a security vulnerability that occurs in the database layer of an application. The vulnerability
is present when user input is either incorrectly filtered
for string literal escape characters embedded in SQL
statements or user input is not strongly typed and thereby
unexpectedly executed. It is in fact an instance of a more
general class of vulnerabilities that can occur whenever
one programming or scripting language is embedded inside another.

Validation is usually done using client-side script like
javascript, jscript, vbscript (javascript being the most
popular due to browser compatibility).

.NET provides 5 + 1 controls for validation
1- RequiredFieldValidator
2- RangeValidator
3- RegularExpressionValidator
4- CompareValidator
5- CustomValidator
 and the ValidationSummary Control

7.What does the "EnableViewState" property do? Why
would I want it on or off?
Ans.
It keeps the data of the control during post backs.
if we turn off, the values should not populate during
server round trip. Basically its used to sustain value
of control's attributes betwen postbacks.

When a form is submitted in classic ASP, all form values
are cleared. Suppose you have submitted a form with a lot of
information and the server comes back with an error. You will
have to go back to the form and correct the information. You
click the back button, and what happens.......
ALL form values are CLEARED, and you will have to start all
over again! The site did not maintain your ViewState.

When a form is submitted in ASP .NET, the form reappears in
the browser window together with all form values. How come?
This is because ASP .NET maintains your ViewState. The ViewState indicates the status of the page when submitted to the server.

The status is defined through a hidden field placed on each page
with a <form runat="server"> control.

Maintaining the ViewState is the default setting for ASP.NET
Web Forms. If you want to NOT maintain the ViewState, include
the directive <%@ Page EnableViewState="false" %> at the top of an .aspx page or add the attribute EnableViewState="false" to any control.

8. What is the difference between Server.Transfer and
Response.Redirect? Why would I choose one over the other?

Ans. Server.Transfer will prevent round trip. it will
redirect pages which or in the same directory. NO way to
pass the query strings . Thru http context we can able
to get the previous page control values.

Response.Redirect : There is a round trip to process the
request. We can redirect to any page external / internal
other than aspx. We can pass the query string thru which we
can manage sessions.

A common misconception is the difference between Server.Transfer and Response.Redirect in ASP.NET applications. Redirect and Transfer both cause a new page to be processed, but the interaction between the client (web browser) and server
(ASP.NET) is different in each situation.

Redirect: A redirect is just a suggestion – it’s like saying
to the client “Hey, you might want to look at this”. All you tell the client is the new URL to look at, and if they comply,
they do a second request for the new URL.

If you want to pass state from the source page to the new
page, you have to pass it either on the URL (such as a database key, or message string), or you can store it in the Session
object (caveat: there may be more than one browser window, and they’ll all use the same session object).

e.g. Redirect to the new.aspx page, passing an ID on the
query string. "true" stops processing the current page:

Response.Redirect("new.aspx?id=32", true);

Transfer: A transfer happens without the client knowing
– it’s the equivalent of a client requesting one page,
but being given another. As far as the client knows, they
are still visiting the original URL.

Sharing state between pages is much easier using
Server.Transfer – you can put values into the Context.Items
dictionary, which is similar to Session and Application,
except that it lasts only for the current request. (search
for HttpContext in MSDN). The page receiving postback can
process data, store values in the Context, and then Transfer
to a page that uses the values. e.g. Store a message in the context dictionary, and transfer to the default.aspx page (which can then display the message):

Context.Items["Message"] = "Your password was changed successfully";
Server.Transfer("default.aspx");

Response.Redirect is more user-friendly, as the site visitor can
bookmark the page that they are redirected to. Transferred pages appear to the client as a different url than they really are.
This means that things like relative links/image paths may not
work if you transfer to a page from a different directory.
Server.Transfer has an optional parameter to pass the form data
to the new page. Since the release version, this no longer works, because the Viewstate now has more security by default (The
EnableViewStateMac defaults to true), so the new page isn’t able to access the form data. You can still access the values of the original page in the new page, by requesting the original handler:

Page originalPage = (Page)Context.Handler;

TextBox textBox1 = (TextBox)originalPage.FindControl("textBox1");

 

9. Can you give an example of when it would be appropriate
to use a web service as opposed to a non-serviced .NET
component.
Ans.
Web service is one of main component in Service Oriented
Architecture. You could use web services when your clients and servers are running on different networks and also different platforms. This provides a loosely coupled system. And also if the client is behind the firewall it would be easy to use web service since it runs on port 80 (by default) instead of having some thing else in Service Oriented Architecture applications.
What is the standard you use to wrap up a call to a Web service?
Ans. SOAP.

Web services are best suite for Hetrogenious
environment. Remoting is best suite for Homogenious environment where the system is under CLR.

10. Let's say I have an existing application written using
Visual Studio 6 (VB 6, InterDev 6) and this application utilizes Windows 2000 COM+ transaction services. How would you approach migrating this application to .NET?

Ans. .NET has made excellent use of the existing COM+
Technology to provide component features like instance management, transactions, activity-based synchronization,
granular role-based security, disconnected asynchronous queued
components, and loosely coupled events. This integration is a
big leap forward, providing greater flexibility to developers
through code.

The .NET components, which make use of the COM+ Services, are termed as ServicedComponents. Must read this link to learn more : http://msdn2.microsoft.com/en-us/library/ms973809.aspx


11. Can you explain the difference between an ADO.NET
Dataset and ADO Recordset?
Ans.
In ADO, the in-memory representation of data is the
recordset. In ADO.NET, it is the dataset. There are important differences between them.

Number of Tables
A recordset looks like a single table. If a recordset is to contain data from multiple database tables, it must use a JOIN query, which assembles the data from the various database tables into a single result table. In contrast, a dataset is a collection of one or more tables. The tables within a dataset are called data tables; specifically, they are DataTable objects. If a dataset contains data from multiple database tables, it will typically contain multiple DataTable objects. That is, each DataTable object typically corresponds to a single database table or view. In this way, a dataset can mimic the structure of the underlying database.

A dataset usually also contains relationships. A relationship within a dataset is analogous to a foreign-key relationship in a database —that is, it associates rows of the tables with each other. For example, if a dataset contains a table about investors and another table about each investor's stock purchases, it could also contain a relationship connecting each row of the investor table with the corresponding rows of the purchase table. Because the dataset can hold multiple, separate tables and maintain information about relationships between them, it can hold much richer data structures than a recordset, including self-relating tables and tables with many-to-many relationships.


Data Navigation and Cursors
In ADO you scan sequentially through the rows of the recordset using the ADO MoveNext method. In ADO.NET, rows are represented as collections, so you can loop through a table as you would through any collection, or access particular rows via ordinal or primary key index. DataRelation objects maintain information about master and detail records and provide a method that allows you to get records related to the one you are working with. For example, starting from the row of the Investor table for "Nate Sun," you can navigate to the set of rows of the Purchase table describing his purchases.

A cursor is a database element that controls record navigation, the ability to update data, and the visibility of changes made to the database by other users. ADO.NET does not have an inherent cursor object, but instead includes data classes that provide the functionality of a traditional cursor. For example, the functionality of a forward-only, read-only cursor is available in the ADO.NET DataReader object. For more information about cursor unctionality, see Data Access Technologies.

Minimized Open Connections
In ADO.NET you open connections only long enough to perform a database operation, such as a Select or Update. You can read rows into a dataset and then work with them without staying connected to the data source. In ADO the recordset can provide disconnected access, but ADO is designed primarily for connected access.

There is one significant difference between disconnected processing in ADO and ADO.NET. In ADO you communicate with the database by making calls to an OLE DB provider. In ADO.NET you communicate with the database through a data adapter (an OleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter object), which makes calls to an OLE DB provider or the APIs provided by the underlying data source. The important difference is that in ADO.NET the data adapter allows you to control how the changes to the dataset are transmitted to the database — by optimizing for performance, performing data validation checks, or adding any other extra processing.

Note -   Data adapters, data connections, data commands, and data readers are the components that make up a .NET Framework data provider. Microsoft and third-party providers can make available other .NET Framework data providers that can be integrated into Visual Studio. For information on the different .NET Data providers, see .NET Data Providers.

Sharing Data Between Applications
Transmitting an ADO.NET dataset between applications is much easier than transmitting an ADO disconnected recordset. To transmit an ADO disconnected recordset from one component to another, you use COM marshalling. To transmit data in ADO.NET, you use a dataset, which can transmit an XML stream.

 

12.  Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines? 

Ans. The Application_Start event is guaranteed to occur only once throughout the lifetime of the application. It’s a good place to initialize global variables. For example, you might want to retrieve a list of products from a database table and place the list in application state or the Cache object. SessionStateModule exposes both Session_Start and Session_End events.


13. If I'm developing an application that must accomodate
multiple security levels through secure login and my ASP.NET web appplication is spanned across three web-servers (using round-robbin load balancing)
what would be the best approach to maintain login-in state
for the users?
Ans.
Database Support OR through State Service

14. What are ASP.NET Web Forms? How is this technology
different than what is available though ASP (1.0-3.0)?
Ans.
There are plenty of differences.
ASP Interpreter.. use the script engine.
ASP.Net is compiled as managed code within the CLR. It also
supports code-behind (unlike in ASP, where code=behind was
invoked through VB components).

15. How does VB.NET/C# achieve polymorphism?
Ans. We achieve it using Function overloading & Operator overloading.

Polymorphism by definition means taking many forms. In C# it means the ability for classes to share the same methods (actions) but implement them differently. For instance, say we create a class called "Shape" and this class has a method called .draw() which draws the shape onto the user interface. Then we create two subclasses, using inheritance, of this Shape class. One called Square, the other called Circle. Now obviously a square and circle are two entirely different shapes, yet both classes have the .draw() method. When the Square.draw() method is called it will draw a square on the user interface. When the Circle.draw() method is called, it will draw a circle on the user interface. So both classes can use the same methods but implement them differently.

PREV NEXT