c# Interview Questions

30
C# Interview Questions 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 questions 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 1. Does C# support multiple-inheritance? No. 2. Who is a protected class-level variable available to? It is available to any sub-class (a class inheriting this class). 3. 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. 4. Describe the accessibility modifier “protected internal”. It is available to classes that are within the same assembly and derived from the specified base class. 5. What’s the top .NET class that everything is derived from? System.Object. 6. 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. 7. 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. 8. 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. 9. Can you store multiple data types in System.Array? No. 10. 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. 11. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods. 12. What’s the .NET collection class that allows an element to be accessed using a unique key? HashTable. 13. What class is underneath the SortedList class? A sorted HashTable. 14. Will the finally block get executed if an exception has not occurred? Yes. 15. What’s the C# syntax to catch any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}. 16. Can multiple catch blocks be executed for a single try statement? No. Once the proper catch block processed, control is transferred to the finally block (if there are any). 17. Explain the three services model commonly know as a three-tier application. Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources). Class Questions 1. What is the syntax to inherit from a class in C#? Place a colon and then the name of the base class. Example: class MyNewClass : MyBaseClass 2. Can you prevent your class from being inherited by another class? Yes. The keyword “sealed” will prevent the class from being inherited. 3. Can you allow a class to be inherited, but prevent the method from being over-ridden? Yes. Just leave the class public and make the method sealed.

Transcript of c# Interview Questions

Page 1: c# Interview Questions

C# Interview Questions

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 questions 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

1. Does C# support multiple-inheritance? No. 

2. Who is a protected class-level variable available to? It is available to any sub-class (a class inheriting this class). 

3. 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.  

4. Describe the accessibility modifier “protected internal”. It is available to classes that are within the same assembly and derived from the specified base class.  

5. What’s the top .NET class that everything is derived from? System.Object.  

6. 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.  

7. 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.  

8. 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. 

9. Can you store multiple data types in System.Array?No.  

10. 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. 

11. How can you sort the elements of the array in descending order?By calling Sort() and then Reverse() methods.  

12. What’s the .NET collection class that allows an element to be accessed using a unique key?HashTable.  

13. What class is underneath the SortedList class?A sorted HashTable.  

14. Will the finally block get executed if an exception has not occurred?Yes.  

15. What’s the C# syntax to catch any possible exception?A catch block that catches the exception of type System.Exception.  You can also omit the parameter data type in this case and just write catch {}.  

16. Can multiple catch blocks be executed for a single try statement?No.  Once the proper catch block processed, control is transferred to the finally block (if there are any).  

17. Explain the three services model commonly know as a three-tier application.Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).  

Class Questions

1. What is the syntax to inherit from a class in C#? Place a colon and then the name of the base class.Example: class MyNewClass : MyBaseClass  

2. Can you prevent your class from being inherited by another class? Yes.  The keyword “sealed” will prevent the class from being inherited.  

3. Can you allow a class to be inherited, but prevent the method from being over-ridden?Yes.  Just leave the class public and make the method sealed.  

4. What’s an abstract class?A class that cannot be instantiated.  An abstract class is a class that must be inherited and have the methods overridden.  An abstract class is essentially a blueprint for a class without any implementation.  

5. When do you absolutely have to declare a class as abstract?1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden. 2.  When at least one of the methods in the class is abstract.  

6. What is an interface class?Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.  

7. Why can’t you specify the accessibility modifier for methods inside the interface?They all must be public, and are therefore public by default.  

8. Can you inherit multiple interfaces?Yes.  .NET does support multiple interfaces.  

Page 2: c# Interview Questions

9. What happens if you inherit multiple interfaces and they have conflicting method names?It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay. To Do: Investigate  

10. What’s the difference between an interface and abstract class?In an interface class, all methods are abstract - there is no implementation.  In an abstract class some methods can be concrete.  In an interface class, no accessibility modifiers are allowed.  An abstract class may have accessibility modifiers.  

11. What is the difference between a Struct and a Class?Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval.  Another difference is that structs cannot inherit.  

Method and Property Questions

1. What’s the implicit name of the parameter that gets passed into the set method/property of a class? Value.  The data type of the value parameter is defined by whatever data type the property is declared as.  

2. What does the keyword “virtual” declare for a method or property? The method or property can be overridden.  

3. How is method overriding different from method overloading? When overriding a method, you change the behavior of the method for the derived class.  Overloading a method simply involves having another method with the same name within the class.  

4. Can you declare an override method to be static if the original method is not static? No.  The signature of the virtual method must remain the same.  (Note: Only the keyword virtual is changed to keyword override)  

5. What are the different ways a method can be overloaded? Different parameter data types, different number of parameters, different order of parameters.  

6. If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor?Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class. 

Events and Delegates

1. What’s a delegate? A delegate object encapsulates a reference to a method.  

2. What’s a multicast delegate? A delegate that has multiple handlers assigned to it.  Each assigned handler (method) is called. 

XML Documentation Questions

1. Is XML case-sensitive? Yes.  

2. What’s the difference between // comments, /* */ comments and /// comments? Single-line comments, multi-line comments, and XML documentation comments.  

3. How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with the /doc switch. 

Debugging and Testing Questions

1. What debugging tools come with the .NET SDK?1.   CorDBG – command-line debugger.  To use CorDbg, you must compile the original C# file using the /debug switch. 2.   DbgCLR – graphic debugger.  Visual Studio .NET uses the DbgCLR.  

2. What does assert() method do? In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false.  The program proceeds without any interruption if the condition is true.  

3. What’s the difference between the Debug class and Trace class? Documentation looks the same.  Use Debug class for debug builds, use Trace class for both debug and release builds.  

4. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose.  For applications that are constantly running you run the risk of overloading the machine and the hard drive.  Five levels range from None to Verbose, allowing you to fine-tune the tracing activities.  

5. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor.  

6. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger.  

7. What are three test cases you should go through in unit testing? 1.       Positive test cases (correct data, correct output).2.       Negative test cases (broken or missing data, proper handling).3.       Exception test cases (exceptions are thrown and caught properly).  

8. Can you change the value of a variable while debugging a C# application? Yes.  If you are debugging via Visual Studio.NET, just go to Immediate window.  

ADO.NET and Database Questions

1. 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.  

2. 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

Page 3: c# Interview Questions

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.  

3. 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%’.  

4. 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.  

5. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password).  

6. 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.  

7. What does the Initial Catalog parameter define in the connection string? The database name to connect to.   

8. 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.  

9. 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. 

Assembly Questions

1. 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.  

2. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.  

3. 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.  

4. What namespaces are necessary to create a localized application? System.Globalization and System.Resources. 

5. What is the smallest unit of execution in .NET?an Assembly. 

6. 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. 

7. How do you convert a value-type to a reference-type?Use Boxing. 

8. 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.

 

Advanced C# interview questions

1. What’s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.

2. Can you store multiple data types in System.Array? No. 3. What’s the difference between the System.Array.CopyTo() and

System.Array.Clone()? The first one performs a deep copy of the array, the second one is shallow.

4. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods.

5. What’s the .NET datatype that allows the retrieval of data by a unique key? HashTable.

6. What’s class SortedList underneath? A sorted HashTable. 7. Will finally block get executed if the exception had not occurred? Yes. 8. What’s the C# equivalent of C++ catch (…), which was a catch-all

statement for any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.

9. Can multiple catch blocks be executed? No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.

10. Why is it a bad idea to throw your own exceptions? Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.

11. What’s a delegate? A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.

12. What’s a multicast delegate? It’s a delegate that points to and eventually fires off several methods.

13. How’s 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.

14. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.

15. What’s 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.

16. What namespaces are necessary to create a localized application? System.Globalization, System.Resources.

17. What’s the difference between // comments, /* */ comments and /// comments? Single-line, multi-line and XML documentation comments.

18. How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with a /doc switch.

Page 4: c# Interview Questions

19. What’s the difference between <c> and <code> XML documentation tag? Single line code example and multiple-line code example.

20. Is XML case-sensitive? Yes, so <Student> and <student> are different elements.

21. What debugging tools come with the .NET SDK? CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.

22. What does the This window show in the debugger? It points to the object that’s pointed to by this reference. Object’s instance data is shown.

23. What does assert() do? In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.

24. What’s the difference between the Debug class and Trace class? Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.

25. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.

26. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor.

27. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger.

28. What are three test cases you should go through in unit testing? Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).

29. Can you change the value of a variable while debugging a C# application? Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.

30. Explain the three services model (three-tier application). Presentation (UI), business (logic and underlying code) and data (from storage or other sources).

31. 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, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.

32. What’s the role of the DataReader class in ADO.NET connections? It returns a read-only dataset from the data source when the command is executed.

33. 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%’.

34. Explain ACID rule of thumb for transactions. Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after).

35. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).

36. 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.

37. Why would you use untrusted verificaion? Web Services might use it, as well as non-Windows applications.

38. What does the parameter Initial Catalog define inside Connection String? The database name to connect to.

39. What’s the data provider name to connect to Access database? Microsoft.Access.

40. What does Dispose method do with the connection object? Deletes it from the memory.

41. 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.

.Net & C# Interview question, along with general programming questions

Hey, These are some Interview Questions with suggested answers we collected in Middle-East-Developers, for more questions in other fields like C++, you can check

the group.These questions are collected by

Adel Khalil

Yehia Megahed

Hisham Abd El-Hafez

Mohammed Hossam

Q1: Can DateTime variables be null?A1: No, because it is a value type (Struct)

Q2: Describe the Asp.net Page Life Cycle?A2: http://msdn2.microsoft.com/en-us/library/ms178472.aspx

Q3: Describe the Asp.net pipeline ? Give an Example when you need to extend it? How do you do so?A3: http://msdn.microsoft.com/msdnmag/issues/02/09/HTTPPipelines/

Q4: Describe the accessibility modifier protected internalA4: Members are accessible to derived classes and classes within the same Assembly

Q5: Difference between an interface and abstract class?A5: In the interface all methods must be abstract, in the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes.

Q6: How do you perform pre- and post-processing to extend a WebMethod ?A6: Use SOAP extensions ...http://msdn.microsoft.com/msdnmag/issues/04/03/ASPColumn/

Q7: What are Design Patterns?A7: It is a big topic in Object Oriented, so for more information see this, http://dofactory.com/Patterns/Patterns.aspx

Q8: What do you know about .net framework 3.0 ?A8: any answer that introduces Windows Communication Foundation (WCF), Windows Workflow Foundation (WF), Windows Presentation Foundation (WPF) and Windows Card Space (WCS) is right, also you can mention that it was originally called WinFX

Q9: What do you know about ATLAS (Microsoft ASP.net AJAX Extensions) ?A9: for more information check here, http://ajax.asp.net

Q10: What do you know about Agile software methodologies?A10: http://en.wikipedia.org/wiki/Agile_software_development

Q11: What do you know about Web Services Enhancements (WSE)?A11: http://msdn.microsoft.com/webservices/webservices/building/wse/default.aspx

Q12: What is AJAX ?A12: Asynchronous Javascript And XML

Q13:What is NUnit, or What is Unit testing?A13: Unit testing: is a procedure used to validate that a particular module of source code is working properly from each modification to the next. The procedure is to write test cases for

Page 5: c# Interview Questions

all functions and methods so that whenever a change causes a regression, it can be quickly identified and fixed. Ideally, each test case is separate from the others; constructs such as mock objects can assist in separating unit tests. This type of testing is mostly done by the developers, NUnit is a famous tool for Unit Testing in .net

Q14: What is an Asp.net Http Handler & Http Module?A14: http://www.15seconds.com/issue/020417.htm

Q15: What is mutable type ? immutable type ?A15: Immutable type are types whose instance data, fields and properties, does not change after the instance is created. Most value types are immutable, but the mutable type are A type whose instance data, fields and properties, can be changed after the instance is created. Most Reference Types are mutable.

Q16: What is the HttpContext Object? Where is it accessible?A16: It's is an Object that Encapsulates all HTTP-specific information about an individual HTTP request. it is avaliable through out the Asp.net request pipline.

Q17: What is the difference between String & StringBuilder classes?A17: String is an immutable type while StringBuilder is a mutable type

Q18: What's the difference between C# 1.0 & C# 2.0?A18: Any answer that introduces stuff like, Generics, Anonymous Methods, Nullable types, Iterators ... etc, is correct

Q19: Without using the multiplication or addition operations, how can you multiply a number x by 8?A19: Shift x to the left 3 times, x << 3, because every shift left multiplies the number by 2

Q20: What is the difference between ASP.net 1.x & ASP.net 2.0 ?A20: Any answer that include stuff like Provider model (membership provider, role provider ... etc) and Master Pages, Code Beside model, new web controls will be ok.

Written by Riley Perry from Distributed Development

OK – here we go, the answers to the first 173.

1. 1.     Name 10 C# keywords.

abstract, event, new, struct, explicit, null, base, extern, object, this

2. 2.     What is public accessibility?

There are no access restrictions.

3. 3.     What is protected accessibility?

Access is restricted to types derived from the containing class.

4. 4.     What is internal accessibility?

A member marked internal is only accessible from files within the same assembly.

5. 5.     What is protected internal accessibility?

Access is restricted to types derived from the containing class or from files within the same assembly.

6. 6.     What is private accessibility?

Access is restricted to within the containing class.

7. 7.     What is the default accessibility for a class?

internal for a top level class, private for a nested one.

8. 8.     What is the default accessibility for members of an interface?

public

9. 9.     What is the default accessibility for members of a struct?

private

10. 10. Can the members of an interface be private?

No.

11. 11. Methods must declare a return type, what is the keyword used when nothing is returned from the method?

void

12. 12. Class methods to should be marked with what keyword?

static

13. 13. Write some code using interfaces, virtual methods, and an abstract class.

using System; public interface Iexample1{

int MyMethod1();} public interface Iexample2{

int MyMethod2();} public abstract class ABSExample : Iexample1, Iexample2{

public ABSExample()

Page 6: c# Interview Questions

{System.Console.WriteLine("ABSExample constructor");

public int MyMethod1(){

return 1;}

 public int MyMethod2(){

return 2;}

 public abstract void MyABSMethod();

} public class VIRTExample : ABSExample{

public VIRTExample(){

System.Console.WriteLine("VIRTExample constructor");}

 public override void MyABSMethod(){

System.Console.WriteLine("Abstract method made concrete");}

 public virtual void VIRTMethod1(){

System.Console.WriteLine("VIRTMethod1 has NOT been overridden");}

 public virtual void VIRTMethod2(){

System.Console.WriteLine("VIRTMethod2 has NOT been overridden");}

} public class FinalClass : VIRTExample{

public override void VIRTMethod2(){

System.Console.WriteLine("VIRTMethod2 has been overridden");}

}

Page 7: c# Interview Questions

14. 14. A class can have many mains, how does this work?

Only one of them is run, that is the one marked (public) static, e.g:

public static void Main(string[] args){

//// TODO: Add code to start application here//

} private void Main(string[] args, int i){}

15. 15. Does an object need to be made to run main?

No

16. 16. Write a hello world console application.

using System; namespace Console1{

class Class1{

[STAThread] // No longer neededstatic void Main(string[] args){

Console.WriteLine("Hello world");}

}

}

17. 17. What are the two return types for main?

void and int

18. 18. What is a reference parameter?

Reference parameters reference the original object whereas value parameters make a local copy and do not affect the original. Some example code is shown:

using System; namespace Console1{

class Class1{

static void Main(string[] args){

TestRef tr1 = new TestRef();TestRef tr2 = new TestRef();

tr1.TestValue = "Original value";tr2.TestValue = "Original value";int tv1 = 1;int tv2 = 1;

 TestRefVal(ref tv1, tv2, ref tr1, tr2);

 Console.WriteLine(tv1);Console.WriteLine(tv2);Console.WriteLine(tr1.TestValue);Console.WriteLine(tr2.TestValue);

 Console.ReadLine();

static public void TestRefVal(ref int tv1Parm, int tv2Parm, ref TestRef tr1Parm, TestRef tr2Parm)

{tv1Parm = 2;tv2Parm = 2;tr1Parm.TestValue = "New value";tr2Parm.TestValue = "New value";

}}

} class TestRef{

public string TestValue;} The output for this is: 21New valueNew value

19. 19. What is an out parameter?

An out parameter allows an instance of a parameter object to be made inside a method. Reference parameters must be initialised but out gives a reference to an uninstanciated object.

20. 20. Write code to show how a method can accept a varying number of parameters.

using System; namespace Console1{

class Class1{

static void Main(string[] args){

ParamsMethod(1,"example");ParamsMethod(1,2,3,4);

Page 8: c# Interview Questions

 Console.ReadLine();

static void ParamsMethod(params object[] list){

foreach (object o in list){

Console.WriteLine(o.ToString());}

}}

}

21. 21. What is an overloaded method?

An overloaded method has multiple signatures that are different.

22. 22. What is recursion?

Recursion is when a method calls itself.

23. 23. What is a constructor?

A constructor performs initialisation for an object (including the struct type) or class.

24. 24. If I have a constructor with a parameter, do I need to explicitly create a default constructor?

Yes

25. 25. What is a destructor?

A C# destuctor is not like a C++ destructor. It is actually an override for Finalize(). This is called when the garbage collector discovers that the object is unreachable. Finalize() is called before any memory is reclaimed.

26. 26. Can you use access modifiers with destructors?

No

27. 27. What is a delegate?

A delegate in C# is like a function pointer in C or C++. A delegate is a variable that calls a method indirectly, without knowing its name. Delegates can point to static or/and member functions. It is also possible to use a multicast delegate to point to multiple functions.

28. 28. Write some code to use a delegate.

Member function with a parameter

using System; namespace Console1{

class Class1{

delegate void myDelegate(int parameter1); 

static void Main(string[] args){

MyClass myInstance = new MyClass();

myDelegate d = new myDelegate(myInstance.AMethod);

d(1); // <--- Calling function without knowing its name.

Test2(d); 

Console.ReadLine();}

 static void Test2(myDelegate d){

d(2); // <--- Calling function without knowing its name.}

class MyClass{

public void AMethod(int param1){

Console.WriteLine(param1);}

}} 

Multicast delegate calling static and member functions

 using System; namespace Console1{

class Class1{

delegate void myDelegate(int parameter1); 

static void AStaticMethod(int param1){

Console.WriteLine(param1);}

 static void Main(string[] args){

MyClass myInstance = new MyClass();

myDelegate d = null;d += new myDelegate(myInstance.AMethod);d += new myDelegate(AStaticMethod);

 d(1); //both functions will be run.

 

Page 9: c# Interview Questions

Console.ReadLine();}

class MyClass{

public void AMethod(int param1){

Console.WriteLine(param1);}

}}

29. 29. What is a delegate useful for?

The main reason we use delegates is for use in event driven programming.

30. 30. What is an event?

See 32

31. 31. Are events synchronous of asynchronous?

Asynchronous

32. 32. Events use a publisher/subscriber model. What is that?

Objects publish events to which other applications subscribe. When the publisher raises an event all subscribers to that event are notified.

33. 33. Can a subscriber subscribe to more than one publisher?

Yes, also - here's some code for a publisher with multiple subscribers.

using System; namespace Console1{

class Class1{

delegate void myDelegate(int parameter1); 

static event myDelegate myEvent;

static void AStaticMethod(int param1){

Console.WriteLine(param1);}

 static void Main(string[] args){

MyClass myInstance = new MyClass();

myEvent += new myDelegate(myInstance.AMethod);myEvent += new myDelegate(AStaticMethod);

 myEvent(1); //both functions will be run.

 Console.ReadLine();

}}

 class MyClass{

public void AMethod(int param1){

Console.WriteLine(param1);}

}} Another example: using System;using System.Threading; namespace EventExample{

public class Clock{

public delegate void TwoSecondsPassedHandler(object clockInstance, TimeEventArgs time); 

//The clock publishes an event that others subscribe topublic event TwoSecondsPassedHandler TwoSecondsPassed;

public void Start(){

while(true){

Thread.Sleep(2000);

//Raise eventTwoSecondsPassed(this, new TimeEventArgs(1));

}}

}public class TimeEventArgs : EventArgs{

public TimeEventArgs(int second){

seconds += second;instanceSeconds = seconds;

private static int seconds;public int instanceSeconds;

public class MainClass{

static void Main(string[] args){

Clock cl = new Clock(); 

// add some subscriberscl.TwoSecondsPassed += new

Clock.TwoSecondsPassedHandler(Subscriber1);cl.TwoSecondsPassed += new

Clock.TwoSecondsPassedHandler(Subscriber2); 

Page 10: c# Interview Questions

cl.Start(); 

Console.ReadLine();}

 public static void Subscriber1(object clockInstance, TimeEventArgs time){

Console.WriteLine("Subscriber1:" + time.instanceSeconds);}

 public static void Subscriber2(object clockInstance, TimeEventArgs time){

Console.WriteLine("Subscriber2:" + time.instanceSeconds);}

}}

34. 34. What is a value type and a reference type?

A reference type is known by a reference to a memory location on the heap. A value type is directly stored in a memory location on the stack. A reference type is essentially a pointer, dereferencing the pointer takes more time than directly accessing the direct memory location of a value type.

35. 35. Name 5 built in types.

Bool, char, int, byte, double

36. 36. string is an alias for what?

System.String

37. 37. Is string Unicode, ASCII, or something else?

Unicode

38. 38. Strings are immutable, what does this mean?

Any changes to that string are in fact copies.

39. 39. Name a few string properties.

trim, tolower, toupper, concat, copy, insert, equals, compare.

40. 40. What is boxing and unboxing?

Converting a value type (stack->heap) to a reference type (heap->stack), and vise-versa.

41. 41. Write some code to box and unbox a value type.

// Boxingint i = 4;object o = i;// Unboxing

i = (int) o;

42. 42. What is a heap and a stack?

There are 2 kinds of heap – 1: a chunk of memory where data is stored and 2: a tree based data structure. When we talk about the heap and the stack we mean the first kind of heap. The stack is a LIFO data structure that stores variables and flow control information. Typically each thread will have its own stack.

43. 43. What is a pointer?

A pointer is a reference to a memory address.

44. 44. What does new do in terms of objects?

Initializes an object.

45. 45. How do you dereference an object?

Set it equal to null.

46. 46. In terms of references, how do == and != (not overridden) work?

They check to see if the references both point to the same object.

47. 47. What is a struct?

Unlike in C++ a struct is not a class – it is a value type with certain restrictions. It is usually best to use a struct to represent simple entities with a few variables. Like a Point for example which contains variables x and y.

48. 48. Describe 5 numeric value types ranges.

sbyte -128 to 127, byte 0 – 255, short -32,768 to 32,767, int -2,147,483,648 to 2,147,483,647, ulong 0 to 18,446,744,073,709,551,615

49. 49. What is the default value for a bool?

false

50. 50. Write code for an enumeration.

public enum animals {Dog=1,Cat,Bear};

51. 51. Write code for a case statement.

switch (n){

case 1:x=1;

Page 11: c# Interview Questions

break;case 2:

x=2;break;

default:goto case 1;

}

52. 52. Is a struct stored on the heap or stack?

Stack

53. 53. Can a struct have methods?

Yes

54. 54. What is checked { } and unchecked { }?

By default C# does not check for overflow (unless using constants), we can use checked to raise an exception. E.g.:

static short x = 32767; // Max short valuestatic short y = 32767; // Using a checked expression public static int myMethodCh() {

int z = 0; 

try {

z = checked((short)(x + y));//z = (short)(x + y);

}catch (System.OverflowException e) {

System.Console.WriteLine(e.ToString());}return z; // Throws the exception OverflowException

} This code will raise an exception, if we remove unchecked as in: 

//z = checked((short)(x + y));z = (short)(x + y);

 Then the cast will raise no overflow exception and z will be assigned –2. unchecked can be used in the opposite way, to say avoid compile time errors with constanst overflow. E.g. the following will cause a compiler error: const short x = 32767; // Max short valueconst short y = 32767; public static int myMethodUnch() {

int z = (short)(x + y);return z; // Returns -2

} The following will not:

 const short x = 32767; // Max short valueconst short y = 32767; public static int myMethodUnch() {

int z = unchecked((short)(x + y));return z; // Returns -2

}

55. 55. Can C# have global overflow checking?

Yes

56. 56. What is explicit vs. implicit conversion?

When converting from a smaller numeric type into a larger one the cast is implicit. An example of when an explicit cast is needed is when a value may be truncated.

57. 57. Give examples of both of the above.

// Implicitshort shrt = 400;int intgr = shrt; // Explicit

shrt = (short) intgr;

58. 58. Can assignment operators be overloaded directly?

No

59. 59. What do operators is and as do?

as acts is like a cast but returns a null on conversion failure. Is comares an object to a type and returns a boolean.

60. 60. What is the difference between the new operator and modifier?

The new operator creates an instance of a class whereas the new modifier is used to declare a method with the same name as a method in one of the parent classes.

61. 61. Explain sizeof and typeof.

typeof obtains the System.Type object for a type and sizeof obtains the size of a type.

62. 62. What doe the stackalloc operator do?

Allocate a block of memory on the stack (used in unsafe mode).

Page 12: c# Interview Questions

63. 63. Contrast ++count vs. count++.

Some operators have temporal properties depending on their placement. E.g.

double x;x = 2;Console.Write(++x);x = 2;Console.Write(x++);Console.Write(x);

Returns

323

64. 64. What are the names of the three types of operators?

Unary, binary, and conversion.

65. 65. An operator declaration must include a public and static modifier, can it have other modifiers?

No

66. 66. Can operator parameters be reference parameters?

No

67. 67. Describe an operator from each of these categories:

Arithmetic: +Logical (boolean and bitwise): &String concatenation: +Increment, decrement: ++Shift: >>Relational: ==Assignment: =Member access: .Indexing: []Cast: ()Conditional: ?:Delegate concatenation and removal: +Object creation: newType information: asOverflow exception control: checkedIndirection and Address: *

68. 68. What does operator order of precedence mean?

Certain operators are evaluated before others. Brackets help to avoid confusion.

69. 69. What is special about the declaration of relational operators?

Relational operators must be declared in pairs.

70. 70. Write some code to overload an operator.

class TempleCompare{ 

public int templeCompareID;public int templeValue;

 public static bool operator == (TempleCompare x, TempleCompare y) { return

(x.templeValue == y.templeValue); }public static bool operator != (TempleCompare x, TempleCompare y) { return !(x

== y); } 

public override bool Equals(object o){

// check types match if (o == null || GetType()!= o.GetType()) return false;TempleCompare t = (templeCompare) o;

return (this.templeCompareID == t.templeCompareID) && (this.templeValue == t.templeValue);

public override int GetHashCode() { return templeCompareID; }}

71. 71. What operators cannot be overloaded?

=, ., ?:, ->, new, is, sizeof, typeof

72. 72. What is an exception?

A runtime error.

73. 73. Can C# have multiple catch blocks?

Yes

74. 74. Can break exit a finally block?

No

75. 75. Can Continue exit a finally block?

No

76. 76. Write some try…catch…finally code.

// try-catch-finallyusing System;

Page 13: c# Interview Questions

public class TCFClass {

public static void Main () {

try {

throw new NullReferenceException();}

 catch(NullReferenceException e) {

Console.WriteLine("{0} exception 1.", e); }

 catch {

Console.WriteLine("exception 2.");}

 finally {

Console.WriteLine("finally block.");}

}}

77. 77. What are expression and declaration statements?         Expression – produces a value e.g. blah = 0         Declaration – e.g. int blah;

78. 78. A block contains a statement list {s1;s2;} what is an empty statement list?

{;}

79. 79. Write some if… else if… code.

int n=4; if (n==1)

Console.WriteLine("n=1"); else if (n==2)

Console.WriteLine("n=2");else if (n==3)

Console.WriteLine("n=3");else

Console.WriteLine("n>3");

80. 80. What is a dangling else?

if (n>0)if (n2>0)

Console.Write("Dangling Else")

else

81. 81. Is switch case sensitive?

Yes

82. 82. Write some code for a for loop

for (int i = 1; i <= 5; i++) Console.WriteLine(i);

83. 83. Can you increment multiple variables in a for loop control?

Yes – e.g. for (int i = 1; j = 2;i <= 5 ;i++ ;j=j+2)

84. 84. Write some code for a while loop.

int n = 1; while (n < 6) {

Console.WriteLine("Current value of n is {0}", n);n++;

}

85. 85. Write some code for do… while.

int x;int y = 0; do {

x = y++;Console.WriteLine(x);

while(y < 5);

86. 86. Write some code that declares an array on ints, assigns the values: 0,1,2,5,7,8,11 to that array and use a foreach to do something with those values.

int x = 0, y = 0;int[] arr = new int [] {0,1,2}; foreach (int i in arr) {

if (i%2 == 0) x++;

else y++;

}

87. 87. Write some code for a custom collection class.

using System;using System.Collections; public class Items : IEnumerable{

Page 14: c# Interview Questions

private string[] contents; 

public Items(string[] contents){

this.contents = contents;}

 public IEnumerator GetEnumerator(){

return new ItemsEnumerator(this);}

 private class ItemsEnumerator : IEnumerator{

private int location = -1;private Items i;

 public ItemsEnumerator(Items i){

this.i = i;}public bool MoveNext(){

if (location < i.contents.Length - 1){

location++;return true;

}else{

return false;}

}public void Reset(){

location = -1;}public object Current{

get{

return i.contents[location];}

}}

 static void Main(){

// Teststring[] myArray = {"a","b","c"};Items items = new Items(myArray);

 foreach (string item in items){

Console.WriteLine(item);}Console.ReadLine();

}

}

88. 88. Describe Jump statements: break, continue, and goto.

Break terminates a loop or switch. Continue jumps to the next iteration of an enclosing iteration statement. Goto jumps to a labelled statement.

89. 89. How do you declare a constant?

public const int c1 = 5;

90. 90. What is the default index of an array?

0

91. 91. What is array rank?

The dimension of the array.

92. 92. Can you resize an array at runtime?

No

93. 93. Does the size of an array need to be defined at compile time.

No

94. 94. Write some code to implement a multidimensional array.

int[,] b = {{0, 1}, {2, 3}, {4, 5}, {6, 7}, {8, 9}};

95. 95. Write some code to implement a jagged array.

// Declare the array of two elements:int[][] myArray = new int[2][]; 

// Initialize the elements:myArray[0] = new int[5] {1,3,5,7,9};

myArray[1] = new int[4] {2,4,6,8};

96. 96. What is an ArrayList?

A data structure from System.Collections that can resize itself.

97. 97. Can an ArrayList be ReadOnly?

Yes

98. 98. Write some code that uses an ArrayList.

Page 15: c# Interview Questions

ArrayList list = new ArrayList();list.Add("Hello");list.Add("World");

99. 99. Write some code to implement an indexer.

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.100.       Can properties have an access modifier?

Yes

101.101.       Can properties hide base class members of the same name?

Yes

102.102.       What happens if you make a property static?

They become class properties.

103.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.104.       Write some code to declare and use properties.

// instancepublic string InstancePr {

get {

return a; }set {

a = value; }

} //read-only staticpublic static int ClassPr {

get {

return b; }

}

105.105.       What is an accessor?

An accessor contains executable statements associated with getting or setting properties.

106.106.       Can an interface have properties?

Yes

107.107.       What is early and late binding?

Late binding is using System.object instead of explicitly declaring a class (which is early binding).

108.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.109.       What is a nested class?

A class declare within a class.

110.110.       What is a namespace?

A namespace declares a scope which is useful for organizing code and to distinguish one type from another.

111.111.       Can nested classes use any of the 5 types of accessibility?

Page 16: c# Interview Questions

Yes

112.112.       Can base constructors can be private?

Yes

113.113.       object is an alias for what?

System.Object

114.114.       What is reflection?

Reflection allows us to analyze an assembly’s metadata and it gives us a mechanism to do late binding.

115.115.       What namespace would you use for reflection?

System.Reflection

116.116.       What does this do? Public Foo() : this(12, 0, 0)

Calls another constructor in the list

117.117.       Do local values get garbage collected?

They die when they are pulled off the stack (go out of scope).

118.118.       Is object destruction deterministic?

No

119.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.120.       What is the using statement for?

The using statement defines a scope at the end of which an object will be disposed.

121.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.122.       Can you derive from a struct?

No

123.123.       Does C# supports multiple inheritance?

No

124.124.       All classes derive from what?

System.Object

125.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.126.       Can different assemblies share internal access?

No

127.127.       Does C# have “friendship”?

Not before C# 2.0

128.128.       Can you inherit from multiple interfaces?

Yes

129.129.       In terms of constructors, what is the difference between: public MyDerived() : base() an public MyDerived() in a child class?

Nothing

130.130.       Can abstract methods override virtual methods?

Yes

131.131.       What keyword would you use for scope name clashes?

this

132.132.       Can you have nested namespaces?

Yes

Page 17: c# Interview Questions

133.133.       What are attributes?

Attributes are declarative tags which can be used to mark certain entities (like methods for example).

134.134.       Name 3 categories of predefined attributes.

COM Interop, Transaction, Visual Designer Component Builder

135.135.       What are the 2 global attributes.

assembly and module.

136.136.       Why would you mark something as Serializable?

To show that the marked type can be serialized.

137.137.       Write code to define and use your own custom attribute.

(From MSDN)

// cs_attributes_retr.csusing 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.138.       List some custom attribute scopes and possible targets.

Assembly – assembly

Class – type

Delegate - type, return

139.139.       List some compiler directives?

#if#else#elif

#endif#define#undef#warning#error#line#region#endregion

140.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.141.       Do you spin off or spawn a thread?

Spin off

142.142.       What is the volatile keyword used for?

It indicates a field can be modified by an external entity (thread, OS, etc.).

143.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{

Page 18: c# Interview Questions

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.144.       What is Monitor?

Monitor is a class that has various functions for thread synchronization.

145.145.       What is a semaphore?

A resource management, synchronization, and locking tool.

146.146.       What mechanisms does C# have for the readers, writers problem?

System.Threading.ReaderWriterLock which has methods AcquireReaderLock, ReleaseReaderLock, AcquireWriterLock, and ReleaseWriterLock

147.147.       What is Mutex?

A Mutex object is used to guarantee only one thread can access a critical resource an any one time.

148.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.149.       What is a DLL?

A set of callable functions, which can be dynamically loaded.

150.150.       What is an assembly identity?

Assembly identity is name, version number, and optional culture, and optional public key to guarantee uniqueness.

151.151.       What does the assembly manifest contain?

Assembly manifest lists all names of public types and resources and their locations in the assembly.

152.152.       What is IDLASM used for?

Use IDLASM to see assembly internals. It disassembles into MSIL.

153.153.       Where are private assemblies stored?

Same folder as exe

154.154.       Where are shared assemblies stored?

The GAC

155.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.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.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.158.       What is unsafe code?

Unsafe code bypasses type safety and memory management.

159.159.       What does the fixed statement do?

Page 19: c# Interview Questions

Prevents relocation of a variable by GC.

160.160.       How would you read and write using the console?

Console.Write, Console.WriteLine, Console.Readline

161.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.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.163.       Are value types are slower to pass as method parameters?

Yes

164.164.       How can you implement a mutable string?

System.Text.StringBuilder

165.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.166.       Describe the CLR security model.

From

http://msdn.microsoft.com/msdnmag/issues/02/09/SecurityinNET/default.aspx

“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.167.       What’s the difference between camel and pascal casing?

PascalCasing, camelCasing

168.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.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.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.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.172.       Describe some common design patterns.

Page 20: c# Interview Questions

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. 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.”

 

Page 21: c# Interview Questions

What Great .NET Developers Ought To Know

Everyone who writes code

← Describe the difference between a Thread and a Process?

← What is a Windows Service and how does its lifecycle differ from a "standard" EXE?

← What is the maximum amount of memory any single process on Windows can

address? Is this different than the maximum virtual memory for the system? How

would this affect a system design?

← What is the difference between an EXE and a DLL?

← What is strong-typing versus weak-typing? Which is preferred? Why?

← Corillian's product is a "Component Container." Name at least 3 component

containers that ship now with the Windows Server Family.

← What is a PID? How is it useful when troubleshooting a system?

← How many processes can listen on a single TCP/IP port?

← What is the GAC? What problem does it solve?

Mid-Level .NET Developer

← Describe the difference between Interface-oriented, Object-oriented and Aspect-

oriented programming.

← Describe what an Interface is and how it’s different from a Class.

← What is Reflection?

← What is the difference between XML Web Services using ASMX and .NET Remoting

using SOAP?

← Are the type system represented by XmlSchema and the CLS isomorphic?

← Conceptually, what is the difference between early-binding and late-binding?

← Is using Assembly.Load a static reference or dynamic reference?

← When would using Assembly.LoadFrom or Assembly.LoadFile be appropriate?

← What is an Asssembly Qualified Name? Is it a filename? How is it different?

← Is this valid? Assembly.Load("foo.dll");

← How is a strongly-named assembly different from one that isn’t strongly-named?

← Can DateTimes be null?

← What is the JIT? What is NGEN? What are limitations and benefits of each?

← How does the generational garbage collector in the .NET CLR manage object

lifetime? What is non-deterministic finalization?

← What is the difference between Finalize() and Dispose()?

← How is the using() pattern useful? What is IDisposable? How does it support

deterministic finalization?

← What does this useful command line do? tasklist /m "mscor*"

← What is the difference between in-proc and out-of-proc?

← What technology enables out-of-proc communication in .NET?

← When you’re running a component within ASP.NET, what process is it running within

on Windows XP? Windows 2000? Windows 2003?

Senior Developers/Architects

← What’s wrong with a line like this? DateTime.Parse(myString);

← What are PDBs? Where must they be located for debugging to work?

← What is cyclomatic complexity and why is it important?

← Write a standard lock() plus “double check” to create a critical section around a

variable access.

← What is FullTrust? Do GAC’ed assemblies have FullTrust?

← What benefit does your code receive if you decorate it with attributes demanding

specific Security permissions?

← What does this do? gacutil /l | find /i "Corillian"

← What does this do? sn -t foo.dll

← What ports must be open for DCOM over a firewall? What is the purpose of Port 135?

Page 22: c# Interview Questions

← Contrast OOP and SOA. What are tenets of each?

← How does the XmlSerializer work? What ACL permissions does a process using it

require?

← Why is catch(Exception) almost always a bad idea?

← What is the difference between Debug.Write and Trace.Write? When should each be

used?

← What is the difference between a Debug and Release build? Is there a significant

speed difference? Why or why not?

← Does JITting occur per-assembly or per-method? How does this affect the working

set?

← Contrast the use of an abstract base class against an interface?

← What is the difference between a.Equals(b) and a == b?

← In the context of a comparison, what is object identity versus object equivalence?

← How would one do a deep copy in .NET?

← Explain current thinking around IClonable.

← What is boxing?

← Is string a value type or a reference type?

← What is the significance of the "PropertySpecified" pattern used by the

XmlSerializer? What problem does it attempt to solve?

← Why are out parameters a bad idea in .NET? Are they?

← Can attributes be placed on specific parameters to a method? Why is this useful?

C# Component Developers

← Juxtapose the use of override with new. What is shadowing?

← Explain the use of virtual, sealed, override, and abstract.

← Explain the importance and use of each component of this string: Foo.Bar,

Version=2.0.205.0, Culture=neutral, PublicKeyToken=593777ae2d274679d

← Explain the differences between public, protected, private and internal.

← What benefit do you get from using a Primary Interop Assembly (PIA)?

← By what mechanism does NUnit know what methods to test?

← What is the difference between: catch(Exception e){throw e;} and catch(Exception

e){throw;}

← What is the difference between typeof(foo) and myFoo.GetType()?

← Explain what’s happening in the first constructor: public class c{ public c(string a) :

this() {;}; public c() {;} } How is this construct useful?

← What is this? Can this be used within a static method?

ASP.NET (UI) Developers

← Describe how a browser-based Form POST becomes a Server-Side event like

Button1_OnClick.

← What is a PostBack?

← What is ViewState? How is it encoded? Is it encrypted? Who uses ViewState?

← What is the <machinekey> element and what two ASP.NET technologies is it used

for?

← What three Session State providers are available in ASP.NET 1.1? What are the pros

and cons of each?

← What is Web Gardening? How would using it affect a design?

← Given one ASP.NET application, how many application objects does it have on a

single proc box? A dual? A dual with Web Gardening enabled? How would this affect

a design?

← Are threads reused in ASP.NET between reqeusts? Does every HttpRequest get its

own thread? Should you use Thread Local storage with ASP.NET?

← Is the [ThreadStatic] attribute useful in ASP.NET? Are there side effects? Good or

bad?

← Give an example of how using an HttpHandler could simplify an existing design that

serves Check Images from an .aspx page.

Page 23: c# Interview Questions

← What kinds of events can an HttpModule subscribe to? What influence can they have

on an implementation? What can be done without recompiling the ASP.NET

Application?

← Describe ways to present an arbitrary endpoint (URL) and route requests to that

endpoint to ASP.NET.

← Explain how cookies work. Give an example of Cookie abuse.

← Explain the importance of HttpRequest.ValidateInput()?

← What kind of data is passed via HTTP Headers?

← Juxtapose the HTTP verbs GET and POST. What is HEAD?

← Name and describe at least a half dozen HTTP Status Codes and what they express

to the requesting client.

← How does if-not-modified-since work? How can it be programmatically implemented

with ASP.NET?

Explain <@OutputCache%> and the usage of VaryByParam, VaryByHeader.

← How does VaryByCustom work?

← How would one implement ASP.NET HTML output caching, caching outgoing versions

of pages generated via all values of q= except where q=5 (as in

http://localhost/page.aspx?q=5)?

Developers using XML

← What is the purpose of XML Namespaces?

← When is the DOM appropriate for use? When is it not? Are there size limitations?

← What is the WS-I Basic Profile and why is it important?

← Write a small XML document that uses a default namespace and a qualified

(prefixed) namespace. Include elements from both namespace.

← What is the one fundamental difference between Elements and Attributes?

← What is the difference between Well-Formed XML and Valid XML?

← How would you validate XML using .NET?

← Why is this almost always a bad idea? When is it a good idea?

myXmlDocument.SelectNodes("//mynode");

← Describe the difference between pull-style parsers (XmlReader) and eventing-

readers (Sax)

← What is the difference between XPathDocument and XmlDocument? Describe

situations where one should be used over the other.

← What is the difference between an XML "Fragment" and an XML "Document."

← What does it meant to say “the canonical” form of XML?

← Why is the XML InfoSet specification different from the Xml DOM? What does the

InfoSet attempt to solve?

← Contrast DTDs versus XSDs. What are their similarities and differences? Which is

preferred and why?

← Does System.Xml support DTDs? How?

← Can any XML Schema be represented as an object graph? Vice versa?

C# developer interview questions

A representative of a high-tech company in United Kingdom sent this in today noting that the list was used for interviewing a C# .NET developer. Any corrections and suggestions would be forwarded to the author. I won’t disclose the name of the company, since as far as I know they might still be using this test for prospective employees. Correct answers are in green color.

1) The C# keyword ‘int’ maps to which .NET type?

1. System.Int16 2. System.Int32

3. System.Int64

4. System.Int128

2) Which of these string definitions will prevent escaping on backslashes in C#?

1. string s = #â€n Test stringâ€; � �2. string s = “’n Test stringâ€; �

3. string s = @â€n Test stringâ€; � �

4. string s = “n Test stringâ€; �

Page 24: c# Interview Questions

3) Which of these statements correctly declares a two-dimensional array in C#?

1. int[,] myArray; 2. int[][] myArray;

3. int[2] myArray;

4. System.Array[2] myArray;

4) If a method is marked as protected internal who can access it?

1. Classes that are both in the same assembly and derived from the declaring class. 2. Only methods that are in the same class as the method in question.

3. Internal methods can be only be called using reflection.

4. Classes within the same assembly, and classes derived from the declaring class.

5) What is boxing?

a) Encapsulating an object in a value type.

b) Encapsulating a copy of an object in a value type.

c) Encapsulating a value type in an object.

d) Encapsulating a copy of a value type in an object.

6) What compiler switch creates an xml file from the xml comments in the files in an assembly?

1. /text 2. /doc

3. /xml

4. /help

7) What is a satellite Assembly?

1. A peripheral assembly designed to monitor permissions requests from an application.

2. Any DLL file used by an EXE file.

3. An assembly containing localized resources for another assembly.

4. An assembly designed to alter the appearance or ‘skin’ of an application.

8) What is a delegate?

1. A strongly typed function pointer. 2. A light weight thread or process that can call a single method.

3. A reference to an object in a different process.

4. An inter-process message channel.

9) How does assembly versioning in .NET prevent DLL Hell?

1. The runtime checks to see that only one version of an assembly is on the machine at any one time.

2. .NET allows assemblies to specify the name AND the version of any assemblies they need to run.

3. The compiler offers compile time checking for backward compatibility.

4. It doesn’t.

10) Which “Gang of Four†design pattern is shown below?�

1. public class A{static private A instance;private A(){}

static public A GetInstance(){if ( instance == null )instance = new A();return instance;}}

1. Factory 2. Abstract Factory

3. Singleton

4. Builder

11) In the NUnit test framework, which attribute must adorn a test class in order for it to be picked up by the NUnit GUI?

1. TestAttribute 2. TestClassAttribute

3. TestFixtureAttribute

Page 25: c# Interview Questions

4. NUnitTestClassAttribute

12) Which of the following operations can you NOT perform on an ADO.NET DataSet?

1. A DataSet can be synchronised with the database. 2. A DataSet can be synchronised with a RecordSet.

3. A DataSet can be converted to XML.

4. You can infer the schema from a DataSet.

13) In Object Oriented Programming, how would you describe encapsulation?

1. The conversion of one type of object to another. 2. The runtime resolution of method calls.

3. The exposition of data.

4. The separation of interface and implementation.

________________vic

What type of class cannot be inherited? A sealed class cannot be inherited. A sealed class is used primarily when the class contains static members. Note that a struct is implicitly sealed; so they cannot be inherited.Name two ways that you can prevent a class from being instantiated?A class cannot be instantiated if it is abstract or if it has a private constructor.Explain some features of interface in C#?Comparison of interface with class (interface vs class):• An interface cannot inherit from a class.• An interface can inherit from multiple interfaces.• A class can inherit from multiple interfaces, but only one class.• Interface members must be methods, properties, events, or indexers• Can an abstract class have non-abstract methods?• An abstract class may contain both abstract and non-abstract methods. But an interface can contain only abstract methods.How do I use an alias for a namespace or class in C#? Use the using directive to create an alias for a long namespace or class. You can then use it anywhere you normally would have used that class or namespace. The using alias has a scope within the namespace you declare it in.Sample code:// Namespace:using act = System.Runtime.Remoting.Activation;// Class:

using list = System.Collections.ArrayList;…list l = new list(); // Creates an ArrayListact.UrlAttribute obj; // Equivalent to System.Runtime.Remoting.Activation.UrlAttribute objWhat keyword must a derived class use to replace a non-virtual inherited method? new keyword is used to replace (not override) an inherited method with one of the same name.What’s the difference between override and new in C#? This is all to do with polymorphism. When a virtual method is called on a reference, the actual type of the object that the reference refers to is used to decide which method implementation to use. When a method of a base class is overridden in a derived class, the version in the derived class is used, even if the calling code didn’t “know” that the object was an instance of the derived class. For instance:public class Base{public virtual void SomeMethod(){}}public class Derived : Base{public override void SomeMethod(){}}…Base b = new Derived();b.SomeMethod();will end up calling Derived.SomeMethod if that overrides Base.SomeMethod.Explain Abstract, Sealed, and Static Modifiers in C#?C# provides many modifiers for use with types and type members. Of these, three can be used with classes: abstract, sealed and static.abstractIndicates that a class is to be used only as a base class for other classes. This means that you cannot create an instance of the class directly. Any class derived from it must implement all of its abstract methods and accessors. Despite its name, an abstract class can possess non-abstract methods and properties.sealedSpecifies that a class cannot be inherited (used as a base class). Note that .NET does not permit a class to be both abstract and sealed.staticSpecifies that a class contains only static members (.NET 2.0).

Page 26: c# Interview Questions

What is the difference between indexers and properties in C#? Comparison Between Properties and IndexersIndexers are similar to properties. Except for the differences shown in the following , all of the rules defined for property accessors apply to indexer accessors as well.

Which interface(s) must a class implement in order to support the foreach statement? Required interface for foreach statement:A class must implement the IEnumerable and IEnumerator interfaces to support the foreach statement.What is the difference between struct and class in C#? Structs vs classes in C#Structs may seem similar to classes, but there are important differences that you should be aware of. First of all, classes are reference types and structs are value types.By using structs, you can create objects that behave like the built-in types and enjoy their benefits as well.When you call the New operator on a class, it will be allocated on the heap. However, when you instantiate a struct, it gets created on the stack. This will yield performance gains. Also, you will not be dealing with references to an instance of a struct as you would with classes. You will be working directly with the struct instance. Because of this, when passing a struct to a method, it’s passed by value instead of as a reference.• Structs can declare constructors, but they must take parameters. It is an error to declare a default (parameterless) constructor for a struct. Struct members cannot have initializers. A default constructor is always provided to initialize the struct members to their default values.• When you create a struct object using the New operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the New operator. If you do not use New, the fields will remain unassigned and the object cannot be used until all the fields are initialized.• There is no inheritance for structs as there is for classes. A struct cannot inherit

from another struct or class, and it cannot be the base of a class. Structs, however, inherit from the base class object. A struct can implement interfaces, and it does that exactly as classes do,• Structs are simple to use and can prove to be useful at times. Just keep in mind that they’re created on the stack and that you’re not dealing with references to them but dealing directly with them. Whenever you have a need for a type that will be used often and is mostly just a piece of data, structs might be a good option.