|
|
C# Interview Questions
Last post Aug 30, 2007, 6:44 AM by Arjun. 13 replies.
-
Jun 09, 2007, 6:54 AM |
-
Arjun
-
-
-
Joined on Jun 01, 2007
-
-
Posts 153
-
-
|
Hi All,
This is a list of questions I have gathered from other sources and created myself over a period of time from my experience, many of which I felt where incomplete or simply wrong. I have finally taken the time to go through each question and correct them to the best of my ability. However, please feel free to post feedback to challenge, improve, or suggest new questions. I want to thank those of you that have contributed quality questions and corrections thus far.
General Questions
Does C# support multiple-inheritance? No. Who is a protected class-level variable available to? It is available to any sub-class (a class inheriting this class). Are private class-level variables inherited? Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited. Describe the accessibility modifier “protected internal”. It is available to classes that are within the same assembly and derived from the specified base class. What’s the top .NET class that everything is derived from? System.Object. What does the term immutable mean? The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory. What’s the difference between System.String and System.Text.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. What’s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created. Can you store multiple data types in System.Array? No. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods. What’s the .NET collection class that allows an element to be accessed using a unique key? HashTable. What class is underneath the SortedList class? A sorted HashTable. Will the finally block get executed if an exception has not occurred? Yes.
What happens in memory when you Box and Unbox a value-type? Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack.
|
|
-
Jun 09, 2007, 7:19 AM |
-
Nitin.k
-
-
-
Joined on Jun 09, 2007
-
-
Posts 7
-
-
|
Re: C# Interview Questions
Thanks Arjun for such a valuable question bank.
Here is one point I got stuck in my application
Why does my Windows application pop up a console window every time I run it?
Thanks in advance
|
|
-
Jun 09, 2007, 8:25 AM |
-
Arjun
-
-
-
Joined on Jun 01, 2007
-
-
Posts 153
-
-
|
Re: C# Interview Questions
Hi dear,
You can check that the target type set in the project properties setting is set to Windows Application, and not Console Application. If you’re using the command line, compile with /target:winexe, not /target:exe.
Hope this will be useful to you.:(
|
|
-
Jun 09, 2007, 9:37 AM |
-
AjayArora
-
-
-
Joined on May 31, 2007
-
India
-
Posts 193
-
-
|
Re: C# Interview Questions
Same problem with my application.. how to check compilation mode?
plz help
thankx in advance
Ajay Arora http://www.roots2india.com ( Indian community ) http://www.primeyards.com ( real estate india )
|
|
-
Jun 11, 2007, 12:52 AM |
-
Arun Arora
-
-
-
Joined on Jun 11, 2007
-
-
Posts 204
-
-
|
Re: C# Interview Questions
Hi Arjun.
I wanted to add some more basic questions asked in most interviews.
What is a Delegate? A strongly typed function pointer. A delegate object encapsulates a reference to a method. When actual function needs to be called will be decided at run-time.
Static Variable and Its Life-Time: VB.NET: Public Shared VAR As Type. C#: public static Type VAR; Life time is till the class is in memory.
Constructor: Special Method Always called whenever an instance of the class is created.
Destructor/Finalize: Called by GC just before object is being reclaimed by GC.
ASP.Net
Different Types of Caching? Output Caching: stores the responses from an asp.net page. Fragment Caching: Only caches/stores the portion of page (User Control) Data Caching: is Programmatic way to Cache objects for performance.
Authentication and Authorization: Authentication is identifying/validating the user against the credentials (username and password) and Authorization performs after authentication. Authorization allowing access of specific resource to user.
Different Types of Directives: Page, Register, Control, OutputCache, Import, Implements, Assembly, Reference
Difference between Server-Side and Client-Side: Server-Side code is executed on web-server and does not transmitted to client, while client-side code executed on client(browser) and is rendered to client along with the content.
Difference Server.Transfer and Response.Redirect: Both ends the processing for the current request immediately. Server.Transfer start executing the another resource specified as parameter without acknowledgement to client(browser) while Response.Redirect intimate client that your requested resource is available at this location and then client request for that resource.
Different Types of Validators and Validation Controls: RequiredFieldValidator, RangeValidator, RegularExpressionValidator, CompareValidator, CustomValidator, ValidationSummary
How to Manage State in ASP.Net? Client based: ViewState, QueryString and Cookies Server based: Session, Application.
Difference between User Control and Custom Control: CUSTOM Controls are compiled code (Dlls), easier to use, difficult to create, and can be placed in toolbox. Drag and Drop controls. Attributes can be set visually at design time. Can be used by Multiple Applications (If Shared Dlls), Even if Private can copy to bin directory of webApp add reference and use. Normally designed to provide common functionality independent of consuming Application.
3 Types of Session State Modes? InProc(cookieless, timeout), StateServer (Server, Port stateConnectionString="tcpip=server:port"), SQLServer (sqlconnectionstring) and Off.
What is ViewState and How it is managed, Its Advantages/Benefits? ViewState is a special object that ASP.NET uses to maintain the state of page and all webcontrols/ServerControls within it. It is in this object preserves the states of various FORM elements during post-backs. It is rendered to client(browser) as a Hidden variable __VIEWSTATE under <form>tag. We can also add custom values to it.
What is web.config and machine.config: machine.config is default configuration for all applications running under this version, located in %WinDir%\Microsfot.Net\Framework\Version. Settings can be overridden by Web.Config for an specific application Web.Config resides in application’s root/virtual root and exists in sub-sequent folders.
Role of Global.asax: Optional file contains the code to handle Application level events raised by ASP.Net or By HttpModule. This file resides in application root directory. Application_Start, _End, _AuthenticateRequest, _Error, Session_Start, _End, BeginRequest, EndRequest. This file is parsed and compiled into dynamically generated class derived from HttpApplication.
Page Life Cycle: Init, LoadViewState, LoadPostBackData, Load, RaisePostBackDataChangedEvent, RaisePostBackEvents, Pre-Render, SaveViewState, Render, Unload, (IpostBackDataChangedEventHandler and IpostBackEventHandler) Error, CommitTransaction, AbortTransaction, Abort inetinfo.exe, aspnet_isapi.dll aspnet_wp.exe, HttpModules (OutputCache, Session, Authentication, Authorization, Custom Modules Specified) and Then HttpHandlers PageHandlerFactory for *.aspx
Can the action attribute of a server-side <form>tag be set to a value and if not how can you possibly pass data from a form to a subsequent Page? No assigning value will not work because will be overwritten at the time of rendering. We can assign value to it by register a startup script which will set the action value of form on client-side. Rest are Server.Transfer and Response.Redirect.
ASP.Net List Controls and differentiate between them? RadioButtonList, CheckBoxList, DropDownList, Repeater, DataGrid, DataList
Type Of Code in Code-Behind class: Server-Side Code.
|
|
-
Jun 18, 2007, 3:16 AM |
-
somender
-
-
-
Joined on Jun 18, 2007
-
-
Posts 1
-
-
|
Re: C# Interview Questions
Hi Arjun
About the multiple Inheritance in C# ...
There is a slight catch here.as you can implement it in C# but using Interfaces...you can use at most one instantiating class while inherting but the no os Interfaces could be of any number.... This is very handy at the design time when the Design of the modules gets fixed to implement certain functionality in the subsequent modules.
|
|
-
Jun 18, 2007, 6:19 AM |
-
Arjun
-
-
-
Joined on Jun 01, 2007
-
-
Posts 153
-
-
|
Re: C# Interview Questions
Hi Somender,
Yeah , it support through Interface. Anyway thanxs and congratulation to have such catchy eyes. :)
Cheer!
|
|
-
Jun 23, 2007, 1:22 AM |
-
manjeet
-
-
-
Joined on Jun 23, 2007
-
chandigarh
-
Posts 1
-
-
|
Re: C# Interview Questions
HI Arjun,
tnx for such a good matterial for interview.That will help me for my prepration for cracking the interview. Thnx once again... i m lookin forwars for more question.hope i will get more from you.. cya Manjeet Software Developer.
Er. Manjeet Rohilla Software Developer
|
|
-
Jun 24, 2007, 10:56 PM |
-
Arjun
-
-
-
Joined on Jun 01, 2007
-
-
Posts 153
-
-
|
Hi, Manjeet
Here's some qestions related to Assembly. Hope it will do some favour to you.
- How is the DLL Hell problem solved in .NET?
Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.
- What are the ways to deploy an assembly?
An MSI installer, a CAB archive, and XCOPY command.
- What is a satellite assembly?
When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
- What namespaces are necessary to create a localized application?
System.Globalization and System.Resources.
- What is the smallest unit of execution in .NET?
an Assembly.
- When should you call the garbage collector in .NET?
As a good rule, you should not call the garbage collector. However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. However, this is usually not a good practice.
- How do you convert a value-type to a reference-type?
Use Boxing.
- What happens in memory when you Box and Unbox a value-type?
Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack.
Good Luck.
|
|
-
-
Jun 24, 2007, 11:00 PM |
-
Arjun
-
-
-
Joined on Jun 01, 2007
-
-
Posts 153
-
-
|
ADO.NET and Database Questions
- What is the role of the DataReader class in ADO.NET connections?
It returns a read-only, forward-only rowset from the data source. A DataReader provides fast access when a forward-only sequential read is needed.
- What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a .NET layer on top of the OLE layer, so it’s not as fastest and efficient as SqlServer.NET.
- What is the wildcard character in SQL?
Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.
- Explain ACID rule of thumb for transactions.
A transaction must be: 1. Atomic - it is one unit of work and does not dependent on previous and following transactions. 2. Consistent - data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t. 3. Isolated - no transaction sees the intermediate results of the current transaction). 4. Durable - the values persist if the data had been committed even if the system crashes right after.
- What connections does Microsoft SQL Server support?
Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password).
- Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted?
Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.
- What does the Initial Catalog parameter define in the connection string?
The database name to connect to.
- What does the Dispose method do with the connection object?
Deletes it from the memory. To Do: answer better. The current answer is not entirely correct.
- What is a pre-requisite for connection pooling?
Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings. The connection string must be identical.
|
|
-
Jun 24, 2007, 11:16 PM |
-
Arjun
-
-
-
Joined on Jun 01, 2007
-
-
Posts 153
-
-
|
C# Frequently Asked Questions
Visual Studio offers tons of useful debugging features and allows you to step through your code line-by-line. However, there are times when you don’t want to step through your application, but want to make it output simple text strings with variable values, etc.
Enter the System.Diagnostics.Debug class and its Write* methods. By using the Debug class, you can output messages similarly to the way the Win32 API function OutputDebugString. However, the beauty of the Debug class is that when you build your application using the default Release configuration in Visual Studio, no code lines are generated for your Debug.Write* class. This means there’s no performance penalty for using the Debug class in release code.
To use the Debug class, simply add the “using System.Diagnostics;” statement to your C# code file, and call Debug.Write: Debug.Write("Hello, Debugger!");
In addition to Write, you have the possibility to call WriteIf, WriteLine and WriteLineIf. For example: bool @this = true;
bool that = false;
Debug.WriteLineIf(@this || that, "A conditional Hello!");
When you are debugging your application under the Visual Studio debugger, all the messages that are sent out by your Write method calls end up in the Output window (View / Output menu command or Ctrl+W,O on the keyboard). However, if you are running your application outside the debugger (say, by starting it from Windows Explorer), you can still view the messages using tools like DebugView from Sysinternals.
Remember, if you build your application using the default Release configuration, even DebugView won’t show your messages because the Debug.Write* calls are eliminated altogether. You can also control code generation by defining the DEBUG conditional directive.
Tip: The .NET debugging/tracing architecture also allows you to redirect debugging messages to different destinations, such as text files. See the help topic “Trace Listeners” for more information
Often, you need a way to monitor your applications once they are running on the server or even at the customer site -- away from your Visual Studio debugger. In those situations, it is often helpful to have a simple routine that you can use to log messages to a text file for later analysis.
Here’s a simple routine that has helped me a lot for example when writing server applications without an user interface: using System.IO;
public string GetTempPath()
{
string path = System.Environment.GetEnvironmentVariable("TEMP");
if (!path.EndsWith("\\")) path += "\\";
return path;
}
public void LogMessageToFile(string msg)
{
System.IO.StreamWriter sw = System.IO.File.AppendText(
GetTempPath() + "My Log File.txt");
try
{
string logLine = System.String.Format(
"{0:G}: {1}.", System.DateTime.Now, msg);
sw.WriteLine(logLine);
}
finally
{
sw.Close();
}
}
With this simple method, all you need to do is to pass in a string like this: LogMessageToFile("Hello, World");
The current date and time are automatically inserted to the log file along with your message. | |
All the /target: options except module create .NET assemblies. Depending on the option, the compiler adds metadata for the operating system to use when loading the portable executable (PE) file and for the runtime to use in executing the contained assembly or module.
module creates a module. The metadata in the PE does not include a manifest. Module/s + manifest make an assembly - the smallest unit of deployment. Without the metadata in the manifest, there is little the runtime can do with a module.
library creates an assembly without an entry point, by setting the EntryPointToken of the PE's CLR header to 0. If you look at the IL, it does not contain the .entrypoint clause. The runtime cannot start an application if the assembly does not have an entry point.
exe creates an assembly with an entry point, but sets the Subsystem field of the PE header to 3 (Image runs in the Windows character subsystem - see the _IMAGE_OPTIONAL_HEADER structure in winnt.h). If you ILDASM the PE, you will see this as .subsystem 0x0003. The OS launches this as a console app.
winexe sets the Subsystem field to 2. (Image runs in the Windows GUI subsystem). The OS launches this as a GUI app |
The difference is that the value of a static readonly field is set at run time, and can thus be modified by the containing class, whereas the value of a const field is set to a compile time constant.
In the static readonly case, the containing class is allowed to modify it only
- in the variable declaration (through a variable initializer)
- in the static constructor (instance constructors, if it's not static)
static readonly is typically used if the type of the field is not allowed in a const declaration, or when the value is not known at compile time.
Instance readonly fields are also allowed.
Remember that for reference types, in both cases (static and instance) the readonly modifier only prevents you from assigning a new reference to the field. It specifically does not make immutable the object pointed to by the reference.
class Program
{
public static readonly Test test = new Test();
static void Main(string[] args)
{
test.Name = "Program";
test = new Test(); // Error: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
}
}
class Test
{
public string Name;
}
On the other hand, if Test were a value type, then assignment to test.Name would be an error.
|
Strictly speaking you can't, since const can only be applied to a field or local whose value is known at compile time.
In both the lines below, the right-hand is not a constant expression (not in C#). const int [] constIntArray = newint [] {2, 3, 4};
// error CS0133: The expression being assigned to 'constIntArray' must be constant
const int [] constIntArrayAnother = {2, 3, 4};
// error CS0623: Array initializers can only be used in a variable or field
// initializer. Try using a new expression instead.
However, there are some workarounds, depending on what it is you want to achieve.
If want a proper .NET array (System.Array) that cannot be reassigned, then static readonly will do for you. static readonly int [] constIntArray = new int[] {1, 2, 3};
The constIntArray field will be initialized before it its first use.
If, on the other hand, you really need a const set of values (say as an argument to an attribute constructor), then - if you can limit yourself to integral types - an enum would serve you well.
For example: [Flags]
public enum Role
{
Administrator = 1,
BackupOperator = 2,
// etc.
}
public class RoleAttribute : Attribute
{
public RoleAttribute()
{
CreateRole = DefaultRole;
}
public RoleAttribute(Role role)
{
CreateRole = role;
}
public Role CreateRole
{
get { return this.createRole; }
set { this.createRole = value; }
}
private Role createRole = 0;
public const Role DefaultRole = Role.Administrator
| Role.BackupOperator;
}
[RoleAttribute(RoleAttribute.DefaultRole)]
public class DatabaseAccount
{
//..............
}
RoleAttribute, instead of taking an array, would only take a single argument of flags (appropriately or-ed). If the underlying type of the Role enum is long or ulong, that gives you 64 different Roles.
|
As you most likely know by now, the Add References dialog of Visual Studio .NET does not list each and every assembly on your machine, does not directly map to the Global Assembly Cache and does not list your custom assemblies. Typically this limitation is addressed by manually navigating to the *.dll of interest via the 'Browse' button.
However, if you wish to force VS.NET to display your custom assemblies within in the list maintained by the Add Reference dialog, all you need to do is place a copy of the assembly within the 'PublicAssemblies' folder located under C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\IDE. Once you have done so, lo' and behold, your custom *.dlls are listed automatically.
|
|
|
-
Aug 28, 2007, 2:57 AM |
-
sonia
-
-
-
Joined on Jun 28, 2007
-
-
Posts 43
-
-
|
Re: C# Frequently Asked Questions
Hi Guys . Thanks alot for providing such a valuable information in here..
its really a great help...
can anyone tell me something about REFLECTIONS in .net
I need that infor right away....
The Sweetest and Sexiest Sonia
|
|
-
Aug 30, 2007, 6:44 AM |
-
Arjun
-
-
-
Joined on Jun 01, 2007
-
-
Posts 153
-
-
|
Re: C# Frequently Asked Questions
Hi Sonia,
Reflection is the ability to read metadata at runtime. Using reflection, it is possible to uncover the methods, properties, and events of a type, and to invoke them dynamically. Reflection also allows us to create new types at runtime, but in the upcoming example we will be reading and invoking only.
Reflection generally begins with a call to a method present on every object in the .NET framework: GetType. The GetType method is a member of the System.Object class, and the method returns an instance of System.Type. System.Type is the primary gateway to metadata. System.Type is actually derived from another important class for reflection: the MemeberInfo class from the System.Reflection namespace. MemberInfo is a base class for many other classes who describe the properties and methods of an object, including FieldInfo, MethodInfo, ConstructorInfo, ParameterInfo, and EventInfo among others. As you might suspect from thier names, you can use these classes to inspect different aspects of an object at runtime.
|
|
|
|
|