Interview Questions – C#
Interview Questions – C#
1. Are private class-level variables inherited? - Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.
2. Why does DllImport not work for me? - All methods marked with the DllImport attribute must be marked as public static extern.
3. Why does my Windows application pop up a console window every time I run it? - Make sure 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.
4. Why do I get an error (CS1006) when trying to declare a method without specifying a return type? - If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following is an example: // This results in a CS1006 error public static staticMethod (mainStatic obj) // This will work as wanted public static void staticMethod (mainStatic obj)
5. Why do I get a syntax error when trying to declare a variable called checked? - The word checked is a keyword in C#.
6. Why do I get a security exception when I try to run my C# app? - Some security exceptions are thrown if you are working on a network share. There are some parts of the frameworks that will not run if being run off a share (roaming profile, mapped drives, etc.). To see if this is what’s happening, just move the executable over to your local drive and see if it runs without the exceptions. One of the common exceptions thrown under these conditions is System.Security.SecurityException. To get around this, you can change your security policy for the intranet zone, code group 1.2, (the zone that running off shared folders falls into) by using the caspol.exe tool.
7. Why do I get a CS5001: does not have an entry point defined error when compiling? - The most common problem is that you used a lowercase ‘m’ when defining the Main method. The correct way to implement the entry point is as follows: class test { static void Main(string[] args) {} }
8. What optimizations does the C# compiler perform when you use the /optimize+ compiler option? - The following is a response from a developer on the C# compiler team: We get rid of unused locals (i.e., locals that are never read, even if assigned). We get rid of unreachable code. We get rid of try-catch with an empty try. We get rid of try-finally with an empty try. We get rid of try-finally with an empty finally. We optimize branches over branches: gotoif A, lab1 goto lab2: lab1: turns into: gotoif !A, lab2 lab1: We optimize branches to ret, branches to next instruction, and branches to branches.
9. What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname() does not compile)? - The syntax for calling another constructor is as follows: class B { B(int i) { } } class C : B { C() : base(5) // call base constructor B(5) { } C(int i) : this() // call C() { } public static void Main() {} }
10. What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development? - Try using RegAsm.exe. Search MSDN on Assembly Registration Tool.
11. What is the difference between a struct and a class in C#? - From language spec: The list of similarities between classes and structs is as follows. Longstructs can implement interfaces and can have the same kinds of members as classes. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.
12. My switch statement works differently than in C++! Why? - C# does not support an explicit fall through for case blocks. The following code is not legal and will not compile in C#:
switch(x)
{
case 0: // do something
case 1: // do something as continuation of case 0
default: // do something in common with
//0, 1 and everything else
break;
}
To achieve the same effect in C#, the code must be modified as shown below (notice how the control flows are explicit):
class Test
{
public static void Main() {
int x = 3;
switch(x)
{
case 0: // do something
goto case 1;
case 1: // do something in common with 0
goto default;
default: // do something in common with 0, 1, and anything else
break;
}
}
}
13. Is there regular expression (regex) support available to C# developers? - Yes. The .NET class libraries provide support for regular expressions. Look at the System.Text.RegularExpressions namespace.
14. Is there any sample C# code for simple threading? - Yes:
using System;
using System.Threading;
class ThreadTest
{
public void runme()
{
Console.WriteLine("Runme Called");
}
public static void Main(String[] args)
{
ThreadTest b = new ThreadTest();
Thread t = new Thread(new ThreadStart(b.runme));
t.Start();
}
}
15. Is there an equivalent of exit() for quitting a C# .NET application? - Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it’s a Windows Forms app.
16. Is there a way to force garbage collection? - Yes. Set all references to null and then call System.GC.Collect(). If you need to have some objects destructed, and System.GC.Collect() doesn’t seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers().
17. Is there a way of specifying which block or loop to break out of when working with nested loops? - The easiest way is to use goto:
using System;
class BreakExample
{
public static void Main(String[] args) {
for(int i=0; i<3; i++)
{
Console.WriteLine("Pass {0}: ", i);
for( int j=0 ; j<100 ; j++ )
{
if ( j == 10)
goto done;
Console.WriteLine("{0} ", j);
}
Console.WriteLine("This will not print");
}
done:
Console.WriteLine("Loops complete.");
}
}
18. Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace? - There is no way to restrict to a namespace. Namespaces are never units of protection. But if you’re using assemblies, you can use the ‘internal’ access modifier to restrict access to only within the assembly.
LINQ Interview Questions
Which assembly represents the core LINQ API?
System.Query.dll assembly represents the core LINQ API.
What is the use of System.Data.DLinq.dll?
System.Data.DLinq.dll provides functionality to work with LINQ to SQL.
What is the use of System.XML.XLinq.dll?
System.XML.XLinq.dll contains classes to provide functionality to use LINQ with XML.
Why can't datareader by returned from a Web Service's Method
Cos, it's not serializable
What is the LINQ file extension that interacts with Code Behind's objects.
its .dbml
What is the extension of the file, when LINQ to SQL is used?
The extension of the file is .dbml
Why Select clause comes after from clause in LINQ?
The reason is, LINQ is used with C# or other programming languages, which requires all the variables to be declared first. From clause of LINQ query just defines the range or conditions to select records. So that’s why from clause must appear before Select in LINQ.
How LINQ is beneficial than Stored Procedures?
There are couple of advantage of LINQ over stored procedures.
1. Debugging - It is really very hard to debug the Stored procedure but as LINQ is part of .NET, you can use visual studio's debugger to debug the queries.
2. Deployment - With stored procedures, we need to provide an additional script for stored procedures but with LINQ everything gets complied into single DLL hence deployment becomes easy.
3. Type Safety - LINQ is type safe, so queries errors are type checked at compile time. It is really good to encounter an error when compiling rather than runtime exception!
What is LINQ?
It stands for Language Integrated Query. LINQ is collection of standard query operators that provides the query facilities into .NET framework language like C# , VB.NET.
What is a Lambda expression?
A Lambda expression is nothing but an Anonymous Function, can contain expressions and statements. Lambda expressions can be used mostly to create delegates or expression tree types. Lambda expression uses lambda operator => and read as 'goes to' operator.
Left side of this operator specifies the input parameters and contains the expression or statement block at the right side.
Example: myExp = myExp/10;
Now, let see how we can assign the above to a delegate and create an expression tree:
delegate int myDel(int intMyNum);
static void Main(string[] args)
{
//assign lambda expression to a delegate:
myDel myDelegate = myExp => myExp / 10;
int intRes = myDelegate(110);
Console.WriteLine("Output {0}", intRes);
Console.ReadLine();
//Create an expression tree type
//This needs System.Linq.Expressions
Expression<myDel> myExpDel = myExp => myExp /10;
}
Note:
The => operator has the same precedence as assignment (=) and is right-associative.
Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as Where.
C# Threading Questions
1)What is Multi-tasking ?
Its a feature of modern operating systems with which we can run multiple programs at same time example Word,Excel etc.
(2)What is Multi-threading ?
Multi-threading forms subset of Multi-tasking instead of having to switch between programs this feature switches between different parts of the same program.Example you are writing in word and at the same time word is doing a spell check in background.
(3)What is a Thread ?
A thread is the basic unit to which the operating system allocates processor time.
(4)Did VB6 support multi-threading ?
While VB6 supports multiple single-threaded apartments, it does not support a free-threading model, which allows multiple threads to run against the same set of data.
(5)Can we have multiple threads in one App domain ?
One or more threads run in an AppDomain. An AppDomain is a runtime representation of a logical process within a physical process.Each AppDomain is started with a single thread, but can create additional threads from any of its threads. Note :- All threading classes are defined in System.Threading namespace.
(6)Which namespace has threading ?
Systems.Threading has all the classes related to implement threading.Any .NET application who wants to implement threading has to import this namespace. Note :- .NET program always has atleast two threads running one the main program and second the garbage collector.
(7)How can we change priority and what the levels of priority are provided by .NET ?
Thread Priority can be changed by using Threadname.Priority = ThreadPriority.Highest.In the sample provided look out for code where the second thread is ran with a high priority.
Following are different levels of Priority provided by .NET :-
ThreadPriority.Highest
ThreadPriority.AboveNormal
ThreadPriority.Normal
ThreadPriority.BelowNormal
ThreadPriority.Lowest
(8)What does Addressof operator do in background ?
The AddressOf operator creates a delegate object to the BackgroundProcess method. A delegate within VB.NET is a type-safe, object-oriented function pointer. After the thread has been instantiated, you begin the execution of the code by calling the Start() method of the thread
(9)How can you reference current thread of the method ?
"Thread.CurrentThread" refers to the current thread running in the method."CurrentThread" is a public static property.
(10) What's Thread.Sleep() in threading ?
Thread's execution can be paused by calling the Thread.Sleep method. This method takes an integer value that determines how long the thread should sleep. Example Thread.CurrentThread.Sleep(2000).
(11)How can we make a thread sleep for infinite period ?
You can also place a thread into the sleep state for an indeterminate amount of time by calling Thread.Sleep (System.Threading.Timeout.Infinite).To interrupt this sleep you can call the Thread.Interrupt method.
(12) What is Suspend and Resume in Threading ?
It is Similar to Sleep and Interrupt. Suspend allows you to block a thread until another thread calls Thread.Resume. The difference between Sleep and Suspend is that the latter does not immediately place a thread in the wait state. The thread does not suspend until the .NET runtime determines that it is in a safe place to suspend it. Sleep will immediately place a thread in a wait state. Note :- In threading interviews most people get confused with Sleep and Suspend.They look very similar.
(13)What the way to stop a long running thread ?
Thread.Abort() stops the thread execution at that moment itself.
(14)What's Thread.Join() in threading ?
There are two versions of Thread.Join :-
Thread.join().
Thread.join(Integer) this returns a boolean value.
The Thread.Join method is useful for determining if a thread has completed before starting another task. The Join method waits a specified amount of time for a thread to end. If the thread ends before the time-out, Join returns True; otherwise it returns False.Once you call Join the calling procedure stops and waits for the thread to signal that it is done. Example you have "Thread1" and "Thread2" and while executing 'Thread1" you call "Thread2.Join()".So "Thread1" will wait until "Thread2" has completed its execution and the again invoke "Thread1". Thread.Join(Integer) ensures that threads do not wait for a long time.If it exceeds a specific time which is provided in integer the waiting thread will start.
(15)What are Daemon thread's and how can a thread be created as Daemon?
Daemon thread's run in background and stop automatically when nothing is running program.Example of a Daemon thread is "Garbage collector".Garbage collector runs until some .NET code is running or else its idle. You can make a thread Daemon by Thread.Isbackground=true
(16) When working with shared data in threading how do you implement synchronization ?
There are a somethings you need to be careful with when using threads. If two threads (e.g. the main and any worker threads) try to access the same variable at the same time, you'll have a problem. This can be very difficult to debug because they may not always do it at exactly the same time. To avoid the problem, you can lock a variable before accessing it. However, if two threads lock the same variable at the same time, you'll have a deadlock problem. SyncLock x 'Do something with x End SyncLock
(17)Can we use events with threading ?
Yes you can use events with threads , this is one of the technique to synchronize one thread with other.
(18)How can we know a state of a thread?
"ThreadState" property can be used to get detail of a thread.Thread can have one or combination of status.System.Threading.Threadstate enumeration has all the values to detect a state of thread.Some sample states are Isrunning,IsAlive,suspended etc.
(19) What is use of Interlocked class ?
Interlocked class provides methods by which you can achieve following functionalities :-
v increment Values.
v Decrement values.
v Exchange values between variables.
v Compare values from any thread. in a synchronization mode.
Example :- System.Threading.Interlocked.Increment(IntA)
(20) what is a monitor object?
Monitor objects are used to ensure that a block of code runs without being interrupted by code running on other threads. In other words, code in other threads cannot run until code in the synchronized code block has finished. SyncLock and End SyncLock statements are provided in order to simplify access to monitor object.
(21) what are wait handles ?
Twist :- What is a mutex object ? Wait handles sends signals of a thread status from one thread to other thread.There are three kind of wait modes :-
v WaitOne.
v WaitAny.
v WaitAll.
When a thread wants to release a Wait handle it can call Set method.You can use Mutex (mutually exclusive) objects to avail for the following modes.Mutex objects are synchronization objects that can only be owned by a single thread at a time.Threads request ownership of the mutex object when they require exclusive access to a resource. Because only one thread can own a mutex object at any time, other threads must wait for ownership of a mutex object before using the resource. The WaitOne method causes a calling thread to wait for ownership of a mutex object. If a thread terminates normally while owning a mutex object, the state of the mutex object is set to signaled and the next waiting thread gets ownership
(22) what is ManualResetEvent and AutoResetEvent ?
Threads that call one of the wait methods of a synchronization event must wait until another thread signals the event by calling the Set method. There are two synchronization event classes. Threads set the status of ManualResetEvent instances to signaled using the Set method. Threads set the status of ManualResetEvent instances to nonsignaled using the Reset method or when control returns to a waiting WaitOne call. Instances of the AutoResetEvent class can also be set to signaled using Set, but they automatically return to nonsignaled as soon as a waiting thread is notified that the event became signaled.
(23) What is ReaderWriter Locks ?
You may want to lock a resource only when data is being written and permit multiple clients to simultaneously read data when data is not being updated. The ReaderWriterLock class enforces exclusive access to a resource while a thread is modifying the resource, but it allows nonexclusive access when reading the resource. ReaderWriter locks are a useful alternative to exclusive locks that cause other threads to wait, even when those threads do not need to update data.
(24) How can you avoid deadlock in threading ?
A good and careful planning can avoid deadlocks.There so many ways microsoft has provided by which you can reduce deadlocks example Monitor ,Interlocked classes , Wait handles, Event raising from one thread to other thread , ThreadState property which you can poll and act accordingly etc.
(25) What’s difference between thread and process?
A thread is a path of execution that run on CPU, a process is a collection of threads that share the same virtual memory. A process has at least one thread of execution, and a thread always run in a process context. Note:- Its difficult to cover threading interview question in this small chapter.These questions can take only to a basic level.If you are attending interviews where people are looking for threading specialist , try to get more deep in to synchronization issues as that's the important point they will stress.
26) Explain Threading Model. What is STA and MTA Model?
In this type of thread model only one thread is used to run the process remaining process needs to wait . The other processes must wait for the current execution of the thread to complete. The main disadvantage of this model is system idle time and long time to complete of small task.
Apartment Thread Model (Single Thread Apartment Model)
In this model we can have multiple threads executing with in an application. In single threaded apartment (STA) each thread is isolated in a separate apartment underneath the process. Each process can have multiple apartments that can share data between these apartment. Here the application is responsible for defining the time duration of each thread execution under these apartment. All requests are serialized through the Windows message queue such that only a single apartment is accessed at a time and thus only a single thread will be executing at any one time. Advantage of this model over single threaded is that multiple tasks can be processed at one time on the users request instead of just a single user request. This model still lack in performance as it is serialized thread model, task will be performed one after another.
Multi Thread Apartment Model (Free thread Apartment Model)
The Multi Threaded Apartment (MTA) model has a single apartment created underneath the process rather than multiple apartments. This single apartment holds multiple threads rather than just a single thread. No message queue is required because all of the threads are a part of the same apartment and can share. These applications typically execute faster than single threaded and STA because there is less system overhead and can be optimized to eliminate system idle time. These types of applications are complex to program as thread synchronization should be provided as part of the code to ensure that threads do not simultaneously access the same resources. A race condition can occur for the shared resource. Thus it is completely necessary to provide a locking system. When locking is provided this can result in a deadlock of the system.
Interview Questions
1. What is a static class?
2. What is static member?
3. What is static function?
4. What is static constructor?
5. How can we inherit a static variable?
6. How can we inherit a static member?
7. Can we use a static function with a non-static variable?
8. How can we access static variable?
9. Why main function is static?
10. How will you load dynamic assembly? How will create assesblies at run time?
11. What is Reflection?
12. If I have more than one version of one assemblies, then how will I use old version (how/where to specify version number?) in my application?
13. How do you create threading in.NET? What is the namespace for that?
14. What do you mean by Serialize and MarshalByRef?
15. What is the difference between Array and LinkedList?
16. What is Asynchronous call and how it can be implemented using delegates?
17. How to create events for a control? What is custom events? How to create it?
18. If you want to write your own dot net language, what steps you will you take care?
19. Describe the diffeerence between inline and code behind - which is best in a loosely coupled solution?
20. How dot net compiled code will become platform independent?
21. Without modifying source code if we compile again, will it be generated MSIL again?
22. How does you handle this COM components developed in other programming languages in.NET?
23. How CCW (Com Callable Wrapper) and RCW (Runtime Callable Wrappers) works?
24. What are the new thee features of COM+ services, which are not there in COM (MTS)?
25. What are the differences between COM architecture and.NET architecture?
26. Can we copy a COM dll to GAC folder?
27. What is Shared and Repeatable Inheritance?
28. Can you explain what inheritance is and an example of when you might use it?
29. How can you write a class to restrict that only one object of this class can be created (Singleton class)?
30. What are virtual destructures?
31. What is close method? How its different from Finalize and Dispose?
32. What is Boxing and UnBoxing?
33. What is check/uncheck?
34. What is the use of base keyword? Tell me a practical example for base keyword’s usage?
35. What are the different.NET tools which you used in projects?
36. What will do to avoid prior case?
37. What happens when you try to update data in a dataset in.NET while the record is already deleted in SQL Server as backend?
38. What is concurrency? How will you avoid concurrency when dealing with dataset?
39. One user deleted one row after that another user through his dataset was trying to update same row. What will happen? How will you avoid this problem?
40. How do you merge two datasets into the third dataset in a simple manner?
41. If you are executing these statements in commandObject. “Select * from Table1; Select * from Table2″ How you will deal result set?
42. How do you sort a dataset.
43. If a dataset contains 100 rows, how to fetch rows between 5 and 15 only?
44. What is the use of Parameter object?
45. How to generateXML from a dataset and vice versa?
46. How do you implement locking concept for dataset?
47. How will you do Redo and Undo in TextBox control?
48. How to implement DataGrid in.NET? How would you make a combo-box appear in one column of a DataGrid? What are the ways to show data grid inside a data grid for a master details type of tables? If we write any code for DataGrid methods. what is the access specifier used for that methods in the code behind file and why?
49. How can we create Tree control in asp.NET?
50. Write a program in C# to find the angle between the hours and minutes in a clock?
51. Write a program to create a user control with name and surname as data members and login as method and also the code to call it.
52. How can you read 3rd line from a text file?
53. Explain the code behind wors and contrast that using the inline style.
54. Explain different types of HTML, Web and server controls.
55. What are the differences between user control and server control?
56. How server form post-back works?
57. Can the action attribute of a server-side
tag be set to a value and if not how can you possibly pass data from a form page to a subsequent page?
58. How would ASP and ASP.NET apps run at the same time on the same server?
59. What are good ADO.NET object to replace to ADO Recordset object.
60. Explain the differences between Server-side code and Client-side code.
61. What type of code(server or client) is found in a Code-Behind class?
62. Should validation (did the user enter a real date) occur server-side or client-side? Why?
63. What does the “EnableViewState” property do? Why would I want it on or off?
64. What is the difference between Server.Transfer and response.Redirect? Why?
65. Can you give an example of when it would be appropriate to use a web service as opposed to a non-serviced.NET component?
66. Let’s say I have an existing application written using VB6 and this application utilizes Windows 2000 COM+ transaction services. How would you approach migrating this application to.NET?
67. If I am developing an application that must accomodate multiple security levels though secure login and my ASP.NET web application is spanned across three web-servers (using round-robin load balancing). What would be the best approach to maintain login-in state for the users?
68. What are ASP.NET web forms? How is this technology different than what is available though ASP(1.0-3.0)?
69. How does VB.NET achieve polymorphism?
70. How does C# achieve polymorphism?
71. Can you explain what is Inheritance and an example in VB.NET and C# of when you might use it?
72. Describe difference between inline and code-behind?
73. What is loosely coupled solution in.NET?
74. What is diffgram?
75. Where would you use an iHTTPModule and what are the limitations of any approach you might take in implementing one?
76. What are the Advantages and DisAdvantages of viewstate?
77. Describe session handling in a webform, how does it work and what are the limitations?
78. How would you get ASP.NET running in Apache web servers? Explain it’s limitations.
79. What is MSIL and why should my developers need an appreciation of it if at all?
80. Which methos do you invoke on the DataAdapter control to load your generated dataset with data?
81. Can you edit data in Repeater control? How?
82. Which template must you provide, in order to display data in a Repeater control?
83. How can you provide an alternating color scheme in a Repeater control?
84. What property must you set, and what method must you call in your code, in order to bind the data from some data source to the repeater control?
85. What base class do all web forms inherit from?
86. What method do you use to explicitly kill a user’s session? How?
87. How do you turn off cookies for one page in your site? Give an example.
88. Which two properties are on every validation control?
89. What tags do you need to add within the asp:datagrid tags to bind columns manually? Give an example.
90. How do you create a permanent cookie?
91. What tag do you use to add a hyperlink column to the dataGrid?
92. What is the standard you use to wrap up a call to a Web Service?
93. Which method do you use to redirect the user to another page without performing a round trip to the client? How?
94. What is the transport protocol you use to call a Seb Service SOAP?
95. What does WSDL stand for?
96. What property do you have to set to tell the grid which page to go to when using the Pager object?
97. Where on the Internet would you look for Web Services?
98. What tags do you need to add within the asp:datagrid tags to bind columns manually? How?
99. Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?
100. How is a property designated as read-only?
101. Which control would you use if you needed to make sure the values in two different controls matched?
0 comments