using System;
namespace Console1 {
class Class1 {
static void Main(string[] args) {
MyIndexableClass m = new MyIndexableClass();
Console.WriteLine(m[0]);
Console.WriteLine(m[1]);
Console.WriteLine(m[2]);
Console.ReadLine();
} }
class MyIndexableClass {
private string []myData = {"one","two","three"};
public string this [int i]
{
get {
return myData[i];
} set {
myData[i] = value;
} }
} }
100. Can properties have an access modifier?
Yes
101. Can properties hide base class members of the same name?
Yes
102. What happens if you make a property static?
They become class properties.
103. Can a property be a ref or out parameter?
A property is not classified as a variable – it can’t be ref or out parameter.
104. Write some code to declare and use properties.
// instance
public string InstancePr {
get {
return a;
} set {
a = value;
} }
//read-only static
public static int ClassPr {
get {
return b;
} }
105. What is an accessor?
An accessor contains executable statements associated with getting or setting properties.
106. Can an interface have properties?
Yes
107. What is early and late binding?
Late binding is using System.object instead of explicitly declaring a class (which is early binding).
108. What is polymorphism
Polymorphism is the ability to implement the same operation many times. Each derived method implements the operation inherited from the base class in its own way.
109. What is a nested class?
A class declare within a class.
110. What is a namespace?
A namespace declares a scope which is useful for organizing code and to distinguish one type from another.
111. Can nested classes use any of the 5 types of accessibility?
Yes
112. Can base constructors can be private?
Yes
113. object is an alias for what?
System.Object
114. What is reflection?
Reflection allows us to analyze an assembly’s metadata and it gives us a mechanism to do late binding.
115. What namespace would you use for reflection?
System.Reflection
116. What does this do? Public Foo() : this(12, 0, 0)
Calls another constructor in the list
117. Do local values get garbage collected?
They die when they are pulled off the stack (go out of scope).
118. Is object destruction deterministic?
No
119. Describe garbage collection (in simple terms).
Garbage collection eliminates uneeded objects.
1. the new statement allocates memory for an object on the heap.
2. When no objects reference the object it may be removed from the heap (this is a non deterministic process).
3. Finalize is called just before the memory is released.
120. What is the using statement for?
The using statement defines a scope at the end of which an object will be disposed.
121. How do you refer to a member in the base class?
To refer to a member in the base class use:return base.NameOfMethod().
122. Can you derive from a struct?
No
123. Does C# supports multiple inheritance?
No
124. All classes derive from what?
System.Object
125. Is constructor or destructor inheritance explicit or implicit? What
does this mean?
Constructor or destructor inheritance is explicit…. Public Extended : base() this is called the constructor initializer.
126. Can different assemblies share internal access?
No
127. Does C# have “friendship”?
Not before C# 2.0
128. Can you inherit from multiple interfaces?
Yes
129. In terms of constructors, what is the difference between: public
MyDerived() : base() an public MyDerived() in a child class?
Nothing
130. Can abstract methods override virtual methods?
Yes
131. What keyword would you use for scope name clashes?
this
132. Can you have nested namespaces?
Yes
133. What are attributes?
Attributes are declarative tags which can be used to mark certain entities (like methods for example).
134. Name 3 categories of predefined attributes.
COM Interop, Transaction, Visual Designer Component Builder
135. What are the 2 global attributes.
assembly and module.
136. Why would you mark something as Serializable?
To show that the marked type can be serialized.
137. Write code to define and use your own custom attribute.
(From MSDN)
// cs_attributes_retr.cs
using System;
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct, AllowMultiple=true)]
public class Author : Attribute {
public Author(string name) {
this.name = name; version = 1.0;
}
public double version;
string name;
public string GetName() {
return name;
} }
138. List some custom attribute scopes and possible targets.
Assembly – assembly Class – type
Delegate - type, return
139. List some compiler directives?
#if
#else
#elif
#endif
#define
#undef
#warning
#error
#line
#region
#endregion
140. What is a thread?
A thread is a the entity within a process that Windows schedules for execution. A thread has:
• The contents of a set of CPU registers representing the state of the processor.
• 2 stacks, 1 for the thread to use in kernel mode, and 1 for user mode.
• Private storage called Thread Local Storage for use by subsystems, run-time libraries, and DLLs.
• A thread ID.
Threads sometimes have their own security context.
141. Do you spin off or spawn a thread?
Spin off
142. What is the volatile keyword used for?
It indicates a field can be modified by an external entity (thread, OS, etc.).
143. Write code to use threading and the lock keyword.
using System;
using System.Threading;
namespace ConsoleApplication4 {
class Class1 {
[STAThread]
static void Main(string[] args) {
ThreadClass tc1 = new ThreadClass(1);
ThreadClass tc2 = new ThreadClass(2);
Thread oT1 = new Thread(new ThreadStart(tc1.ThreadMethod));
Thread oT2 = new Thread(new ThreadStart(tc2.ThreadMethod));
oT1.Start();
oT2.Start();
Console.ReadLine();
} }
class ThreadClass {
private static object lockValue = "dummy";
public int threadNumber;
public ThreadClass(int threadNumber) {
this.threadNumber = threadNumber;
}
public void ThreadMethod() {
for (;;) {
lock(lockValue) {
Console.WriteLine(threadNumber + " working");
Thread.Sleep(1000);
} }
} }
}
144. What is Monitor?
Monitor is a class that has various functions for thread synchronization.
145. What is a semaphore?
A resource management, synchronization, and locking tool.
146. What mechanisms does C# have for the readers, writers problem?
System.Threading.ReaderWriterLock which has methods AcquireReaderLock, ReleaseReaderLock, AcquireWriterLock, and ReleaseWriterLock
147. What is Mutex?
A Mutex object is used to guarantee only one thread can access a critical resource an any one time.
148. What is an assembly?
Assemblies contain logical units of code in MSIL, metadata, and usually a manifest. Assemblies can be signed and the can dome in the form of a DLL or EXE.
149. What is a DLL?
A set of callable functions, which can be dynamically loaded.
150. What is an assembly identity?
Assembly identity is name, version number, and optional culture, and optional public key to guarantee uniqueness.
151. What does the assembly manifest contain?
Assembly manifest lists all names of public types and resources and their locations in the assembly.
152. What is IDLASM used for?
Use IDLASM to see assembly internals. It disassembles into MSIL.
153. Where are private assemblies stored?
Same folder as exe
154. Where are shared assemblies stored?
The GAC
155. What is DLL hell?
DLLs, VBX or OCX files being unavailable or in the wrong versions. Applicatioins using say these older DLLs expect some behaviour which is not present.
156. In terms of assemblies, what is side-by-side execution?
An app can be configured to use different versions of an assembly simultaneously.
157. Name and describe 5 different documentation tags.
/// <value></value>
/// <example></example>
/// <exception cref=""></exception>
/// <include file='' path='[@name=""]'/>
/// <param name="args"></param>
/// <paramref name=""/>
/// <permission cref=""></permission>
/// <remarks>
/// </remarks>
/// <summary>
/// <c></c>
/// <code></code>
/// <list type=""></list>
/// <see cref=""/>
/// <seealso cref=""/>
/// </summary>
158. What is unsafe code?
Unsafe code bypasses type safety and memory management.
159. What does the fixed statement do?
Prevents relocation of a variable by GC.
160. How would you read and write using the console?
Console.Write, Console.WriteLine, Console.Readline
161. Give examples of hex, currency, and fixed point console formatting.
Console.Write("{0:X}", 250); FA Console.Write("{0:C}", 2.5); $2.50 Console.Write("{0:F2}", 25); 25.00
162. Given part of a stack trace:
aspnet.debugging.BadForm.Page_Load(Object sender, EventArgs e) +34. What does the +34 mean?
It is an actual offset (at the assembly language level) – not an offset into the IL instructions.
163. Are value types are slower to pass as method parameters?
Yes
164. How can you implement a mutable string?
System.Text.StringBuilder
165. What is a thread pool?
A thread pool is a means by which to control a number of threads
simultaneously. Thread pools give us thread reuse, rather than creating a new thread every time.
166. Describe the CLR security model.
From
http://msdn.microsoft.com/msdnmag/issues/02/09/SecurityinNET/default.as px
“Unlike the old principal-based security, the CLR enforces security policy based on where code is coming from rather than who the user is. This model, called code access security, makes sense in today's environment because so much code is installed over the Internet and even a trusted user doesn't know when that code is safe.”
167. What’s the difference between camel and pascal casing?
PascalCasing, camelCasing
168. What does marshalling mean?
From
http://www.dictionary.net/marshalling
“The process of packing one or more items of data into a message buffer, prior to transmitting that message buffer over a communication channel. The packing process not only collects together values which may be stored in
non-consecutive memory locations but also converts data of different types into a standard representation agreed with the recipient of the message.”
169. What is inlining?
From (Google web defintions)
“In-line expansion or inlining for short is a compiler optimization which "expands"
a function call site into the actual implementation of the function which is called, rather than each call transferring control to a common piece of code. This
reduces overhead associated with the function call, which is especially important for small and frequently called functions, and it helps call-site-specific compiler optimizations, especially constant propagation.”
170. List the differences in C# 2.0.
• Generics
• Iterators
• Partial class definitions
• Nullable Types
• Anonymous methods
• :: operator
• Static classes static class members
• Extern keyword
• Accessor accessibility
• Covariance and Contravariance
• Fixed size buffers
• Fixed assemblies
• #pragma warning
171. What are design patterns?
From
http://www.dofactory.com/Patterns/Patterns.aspx
“Design patterns are recurring solutions to software design problems you find again and again in real-world application development.”
172. Describe some common design patterns.
From
http://www.dofactory.com/Patterns/Patterns.aspx Creational Patterns
Abstract Factory Creates an instance of several families of classes
Builder Separates object construction from its representation Factory Method Creates an instance of several derived classes Prototype A fully initialized instance to be copied or cloned Singleton A class of which only a single instance can exist Structural Patterns
Adapter Match interfaces of different classes
Bridge Separates an object’s interface from its implementation Composite A tree structure of simple and composite objects Decorator Add responsibilities to objects dynamically
Façade A single class that represents an entire subsystem Flyweight A fine-grained instance used for efficient sharing Proxy An object representing another object
Behavioral Patterns
Chain of Resp. A way of passing a request between a chain of objects Command Encapsulate a command request as an object
Interpreter A way to include language elements in a program Iterator Sequentially access the elements of a collection Mediator Defines simplified communication between classes Memento Capture and restore an object's internal state Observer A way of notifying change to a number of classes State Alter an object's behavior when its state changes Strategy Encapsulates an algorithm inside a class
Template Method Defer the exact steps of an algorithm to a subclass
Visitor Defines a new operation to a class without change
173. What are the different diagrams in UML? What are they used for?
From
http://www.developer.com/design/article.php/1553851
• “Use case diagram: The use case diagram is used to identify the primary elements and processes that form the system. The primary elements are termed as "actors" and the processes are called "use cases." The use case diagram shows which actors interact with each use case.
• Class diagram: The class diagram is used to refine the use case diagram and define a detailed design of the system. The class diagram classifies the actors defined in the use case diagram into a set of interrelated
classes. The relationship or association between the classes can be either an "is-a" or "has-a" relationship. Each class in the class diagram may be capable of providing certain functionalities. These functionalities provided by the class are termed "methods" of the class. Apart from this, each class may have certain "attributes" that uniquely identify the class.
• Object diagram: The object diagram is a special kind of class diagram.
An object is an instance of a class. This essentially means that an object represents the state of a class at a given point of time while the system is running. The object diagram captures the state of different classes in the system and their relationships or associations at a given point of time.
• State diagram: A state diagram, as the name suggests, represents the different states that objects in the system undergo during their life cycle.
Objects in the system change states in response to events. In addition to this, a state diagram also captures the transition of the object's state from an initial state to a final state in response to events affecting the system.
• Activity diagram: The process flows in the system are captured in the activity diagram. Similar to a state diagram, an activity diagram also consists of activities, actions, transitions, initial and final states, and guard conditions.
• Sequence diagram: A sequence diagram represents the interaction between different objects in the system. The important aspect of a sequence diagram is that it is time-ordered. This means that the exact sequence of the interactions between the objects is represented step by step. Different objects in the sequence diagram interact with each other by passing "messages".
• Collaboration diagram: A collaboration diagram groups together the interactions between different objects. The interactions are listed as numbered interactions that help to trace the sequence of the interactions.
The collaboration diagram helps to identify all the possible interactions that each object has with other objects.
• Component diagram: The component diagram represents the high-level parts that make up the system. This diagram depicts, at a high level, what components form part of the system and how they are interrelated. A component diagram depicts the components culled after the system has undergone the development or construction phase.
• Deployment diagram: The deployment diagram captures the
configuration of the runtime elements of the application. This diagram is by far most useful when a system is built and ready to be deployed.”
C# Interview Questions
(http://blogs.crsw.com/mark/articles/252.aspx)
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.
There are some question in this list that I do not consider to be good questions for an interview. However, they do exist on other lists available on the Internet so I felt compelled to keep them easy access.
General Questions