C# Interview Questions


C# Book

Full List

1. 1. Introduction
1. 1. 3. Program structure
1. 1. 4. Identifiers
1. 1. 5. Keywords
1. 1. 7. Comments
1. 2. Data Types
1. 2. 2. Variable
1. 3. 2. Numeric types
1. 3. 5. Literal suffix
1. 3. 6. Default literal
1. 3. 9. double vs decimal
1. 3. 10. bool type
1. 3. 11. char type
1. 3. 13. string type
1. 3. 18. Determine the order
1. 3. 19. What is an Array
1. 3. 20. Arrays as Objects
1. 3. 21. for loop and array
1. 3. 27. var array type
1. 3. 29. Arrays as Arguments
1. 4. Operators
1. 4. 1. Operators in C#
1. 4. 2. 1. Arithmetic operators
1. 4. 2. 3. Division on integers
1. 4. 2. 4. Divide by zero exception
1. 4. 2. 5. Integral type overflow
1. 4. 2. 6. Check runtime overflow
1. 4. 2. 8. unchecked operator
1. 4. 2. 9. Integral type promotion
1. 4. 2. 10. Infinit real numners
1. 4. 2. 11. Check Not-a-Number
1. 4. 3. Bitwise operators
1. 4. 3. 1. Bitwise operators in C#
1. 4. 4. 2. Conditional shortcut
1. 4. 5. Ternary operator
1. 4. 6. default operator
1. 4. 6. 1. default keyword
1. 4. 6. 2. Default value for struct
1. 5. 2. if statement
1. 5. 2. 1. if statement
1. 5. 2. 2. else branch
1. 5. 2. 3. Nested if statement
1. 5. 3. switch statement
1. 5. 3. 1. switch statement
1. 5. 4. while loop
1. 5. 4. 1. while loop
1. 5. 5. do while loop
1. 5. 5. 1. do...while loop
1. 5. 6. for loop statement
1. 5. 6. 1. for loop
1. 5. 7. foreach statement
1. 5. 7. 1. foreach loop
1. 5. 8. break statement
1. 5. 8. 1. break statement
1. 5. 9. continue statement
1. 5. 9. 1. continue statement
1. 5. 10. return statement
1. 5. 11. goto statement
1. 6. class
1. 6. 2. Class creation
1. 6. 3. Nested types
1. 6. 4. Members
1. 7. Field
1. 7. 1. Class field
1. 7. 3. Read only field
1. 7. 6. const value
1. 8. Method
1. 8. 1. Methods
1. 8. 2. A demo method
1. 8. 4. Method overloading
1. 8. 6. Main functions
1. 9. Constructor
1. 9. 1. Constructor
1. 9. 8. static constructor
1. 10. Parameters
1. 10. 1. Parameters
1. 10. 3. ref modifier
1. 10. 6. Optional parameters
1. 10. 7. Named parameters
1. 11. Properties
1. 11. 1. Properties
1. 11. 2. read only property
1. 11. 3. Automatic property
1. 12. indexer
1. 12. 1. Indexer
1. 12. 2. Your own indexer
1. 13. this
1. 13. 1. this keyword
1. 14. Partial type
1. 14. 1. Partial type
1. 14. 2. Partial method
1. 15. Finalizer
1. 15. 1. Finalizer
1. 16. Inheritance
1. 16. 1. Inheritance
1. 16. 3. base keyword
1. 16. 5. Polymorphism
1. 17. virtual
1. 17. 1. virtual members
1. 17. 3. new and virtual
1. 17. 4. Seal a member
1. 18. 2. Conversion Operator
1. 19. 1. Abstract class
1. 19. 2. Static Class
1. 20. static
1. 20. 1. Static Members
1. 21. as is
1. 21. 1. as operator
1. 21. 2. is operator
1. 22. object
1. 22. 1. object class
1. 22. 2. ToString method
1. 23. 1. Boxing and unboxing
1. 24. var
1. 24. 1. Anonymous Type
1. 25. dynamic
1. 25. 1. dynamic type
1. 26. typeof
1. 27. struct
1. 27. 1. Creating a struct
1. 28. 1. Access modifier
1. 29. interface
1. 29. 1. interface
1. 30. enum
1. 30. 1. enum type
1. 30. 3. enum backend value
1. 30. 5. Build up enum
1. 30. 6. Flag enum
1. 31. generics
1. 31. 1. Generic type
1. 31. 2. Generic methods
1. 31. 4. Type parameters
1. 32. delegate
1. 32. 1. delegate creation
1. 32. 3. Multicast delegate
1. 32. 6. Func and Action
1. 32. 7. delegate variables
1. 33. event
1. 33. 1. Event and delegate
1. 34. lambda
1. 34. 1. lambda Expressions
1. 35. 2. catch statement
1. 35. 3. finally statement
1. 36. 1. using statement
1. 37. 1. Throw exception
1. 37. 2. Rethrow exception
1. 37. 3. System.Exception
1. 38. namespace
1. 38. 1. What is namespace
1. 38. 2. namespace hierarchy
1. 38. 5. namespace scope
1. 38. 7. Hidden types
1. 38. 8. Alias namespace
1. 38. 9. global namespace
1. 39. nullable
1. 39. 1. nullable type
1. 39. 4. ?? operator
1. 40. 1. Anonymous type
1. 41. 1. Extension method
1. 43. unsafe code
1. 43. 1. unsafe code
1. 44. 1. Xml Documentation
1. 45. Debug Trace
1. 45. 2. TraceListener
1. 45. 3. Fail() method
1. 45. 4. Assert
2. 1. Char
2. 1. 1. Char Structure
2. 1. 3. UTF-16 Character
2. 2. String
2. 2. 1. String type
2. 2. 6. Substring index
2. 2. 8. Get the substring
2. 2. 11. Padding string
2. 2. 12. Trim a string
2. 2. 13. Replacing substring
2. 2. 14. Change string case
2. 2. 15. Split string
2. 2. 16. Join string
2. 2. 17. Concatenate strings
2. 2. 18. String format
2. 2. 20. Determine the order
2. 3. 3. Formatted string
2. 3. 6. Reverse a string
2. 4. Encoding
2. 4. 1. Encoding
2. 5. TimeSpan
2. 5. 1. TimeSpan type
2. 5. 2. TimeSpan operators
2. 6. 3. TimeSpan Adding
2. 6. 9. DateTime Kind
2. 7. 1. Current TimeZone
2. 7. 2. Daylight saving
2. 7. 4. Local time
2. 7. 5. Time zone ID
2. 7. 6. All Time zones
2. 8. 1. ToString and Parse
2. 9. Format
2. 9. 27. Enum Format Strings
2. 10. 1. NumberFormatInfo
2. 11. NumberStyles
2. 11. 1. Using NumberStyles
2. 12. Convert
2. 12. 1. Convert class
2. 12. 3. Dynamic conversions
2. 13. BitConverter
2. 13. 1. BitConverter
2. 14. BigInteger
2. 14. 1. BigInteger
2. 14. 2. BigInteger casting
2. 15. Complex
2. 15. 1. Complex
2. 16. Random
2. 16. 1. Random
2. 17. Enum
2. 17. 2. String conversions
2. 18. Tuple
2. 18. 1. Tuples
2. 19. Guid
2. 19. 1. The Guid Struct
2. 20. Console
2. 21. 1. Dynamic Objects
3. 1. Introduction
3. 4. Array
3. 4. 1. Array Class
3. 4. 2. Array Enumeration
3. 4. 3. Length and Rank
3. 4. 4. Array Search
3. 4. 5. Sort an array
3. 4. 6. Array Conversion
3. 5. List
3. 5. 1. List
3. 6. LinkedList
3. 6. 1. Generic LinkedList
3. 7. ArrayList
3. 7. 1. Sorting
3. 7. 2. ArrayList and Linq
3. 8. Queue
3. 9. Stack
3. 10. BitArray
3. 10. 1. BitArray
3. 11. HashSet
3. 11. 1. HashSet
3. 12. SortedSet
3. 13. Dictionary
3. 13. 1. Generic IDictionary
3. 14. SortedList
3. 14. 1. SortedList
4. LINQ
4. 1. Introduction
4. 1. 1. Linq
4. 1. 2. Lambda and Linq
4. 2. Linq Syntax
4. 2. 2. Deferred Execution
4. 2. 4. Captured Variables
4. 2. 5. Subqueries
4. 2. 7. Anonymous Types
4. 2. 8. The let Keyword
4. 3. 1. Aggregate
4. 3. 2. Any
4. 3. 3. Average
4. 3. 4. Cast
4. 3. 5. Concat
4. 3. 6. Contains
4. 3. 7. Count
4. 3. 8. Distinct
4. 3. 9. ElementAt
4. 3. 10. Empty
4. 3. 11. Except
4. 3. 12. First
4. 3. 13. FirstOrDefault
4. 3. 14. GroupBy
4. 3. 15. Intersect
4. 3. 16. Last
4. 3. 17. LongCount
4. 3. 18. Max
4. 3. 19. Min
4. 3. 20. OfType
4. 3. 21. OrderBy
4. 3. 22. OrderByDescending
4. 3. 23. Range
4. 3. 24. Repeat
4. 3. 25. Select
4. 3. 26. SelectMany
4. 3. 27. Single
4. 3. 28. Skip
4. 3. 29. SkipWhile
4. 3. 30. Sum
4. 3. 31. Take
4. 3. 32. TakeWhile
4. 3. 33. ThenBy
4. 3. 34. ThenByDescending
4. 3. 35. Union
4. 3. 36. Where
4. 3. 37. Zip
4. 4. Enumerable
4. 4. 1. Sort
5. 1. XElement
5. 1. 2. Load and parse
5. 1. 5. Replace an Element
5. 2. XAttribute
5. 2. 1. XAttribute
5. 3. XText
5. 3. 1. XText
5. 4. XDocument
5. 4. 1. XDocument
5. 4. 2. XDocument Root
5. 5. 1. XName
5. 5. 2. XNamespace
5. 6. Xml Query
5. 6. 2. All elements
5. 6. 3. XElement and Linq
6. XML
6. 1. XmlReader
6. 1. 1. XmlReader
6. 1. 2. XmlNodeType
6. 2. XmlWriter
6. 2. 1. XmlWriter
6. 2. 2. Writing Attributes
6. 3. XmlDocument
6. 3. 1. XmlDocument
6. 4. XPath
6. 4. 1. XPath
6. 5. Xml Schema
6. 6. XSLT
6. 6. 1. XSLT
7. Stream
7. 1. Stream
7. 1. 1. Streams
7. 1. 2. Stream in action
7. 2. FileStream
7. 2. 1. FileStream
7. 4. 1. File and FileInfo
7. 5. 1. DirectoryInfo
7. 6. Path
7. 6. 1. Path
7. 6. 2. Special Folders
7. 7. DriveInfo
7. 10. Compression
7. 10. 1. Compression
8. Net
8. 1. IPAddress
8. 1. 1. IPAddress
8. 2. Uri
8. 2. 1. Uri
8. 3. WebClient
8. 3. 1. WebProxy
8. 3. 2. Authentication
8. 3. 3. CredentialCache
8. 3. 5. Catch WebException
8. 4. HTTP
8. 4. 2. Query Strings
8. 4. 4. Cookies
8. 5. FTP
8. 5. 1. Using FTP
8. 5. 2. Ftp operations
8. 5. 3. Delete a file
8. 6. DNS
8. 6. 1. Using DNS
8. 7. Mail
8. 8. Tcp
8. 8. 1. Your own server
9. 1. Type
9. 1. 2. Obtaining a Type
9. 1. 3. Type from Assembly
9. 1. 5. Type properties
9. 1. 8. Type Names
9. 1. 9. Nested type names
9. 1. 10. Generic type names
9. 1. 14. Instantiating Types
9. 1. 16. Generic Types
9. 2. Member
9. 2. 2. Get members
9. 2. 3. MemberInfo
9. 2. 6. Method Parameters
9. 3. Assembly
10. Thread
10. 1. Thread
10. 1. 1. Thread
10. 1. 2. Join a Thread
10. 1. 3. Sleep a thread
10. 2. 1. Thread Priority
11. 1. Introduction
11. 1. 2. Regex class
11. 1. 3. Match class
11. 1. 5. Using RegexOptions
11. 1. 6. Character Escapes
11. 2. 1. Character Sets
11. 3. Quantifiers
11. 3. 1. Quantifiers
11. 4. Anchors
11. 4. 1. Anchors
11. 4. 2. Word Boundaries
11. 4. 4. Word count
11. 5. Groups
11. 5. 1. Groups
11. 5. 2. Named Groups
11. 5. 5. Matching a Guid
11. 6. Regex
11. 6. 2. Splitting Text
C# interview questions and answers

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


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.

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

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.

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

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

What’s class SortedList underneath?
A sorted HashTable.

Will finally block get executed if the exception had not occurred?
Yes.

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

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.

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.

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

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

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.

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

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.

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

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

Is XML case-sensitive?
Yes, so and are different elements.

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.

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.

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.

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.

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.

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

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

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

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.

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.

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.

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

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

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

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

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.
1 comments
Labels: C# Interview Questions
C# Interview Questions - 1

Does C# support multiple-inheritance? No.
Who is a protected class-level variable available to? It is available to any sub-class (a class inheriting this class).

Are private class-level variables inherited?
Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited.

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

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

What does the term immutable mean?
The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.

What’s the difference between System.String and System.Text.StringBuilder classes?
System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

What’s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.

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

What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.

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

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

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

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

What’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 {}.

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

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

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

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.

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.

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.

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.

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

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

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

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.

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

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

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.

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)

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

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
What’s a delegate?
A delegate object encapsulates a reference to a method.

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

XML Documentation Questions
Is XML case-sensitive?
Yes.

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

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

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.

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.

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.

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

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

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

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
What is the role of the DataReader class in ADO.NET connections?
It returns a read-only, forward-only rowset from the data source. A DataReader provides fast access when a forward-only sequential read is needed.

What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a .NET layer on top of the OLE layer, so it’s not as fastest and efficient as SqlServer.NET.

What is the wildcard character in SQL?
Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.

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

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

Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted?
Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.

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

What does the Dispose method do with the connection object?
Deletes it from the memory.To Do: answer better. The current answer is not entirely correct.

What is a pre-requisite for connection pooling?
Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings. The connection string must be identical.

Assembly Questions
How is the DLL Hell problem solved in .NET?
Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.

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

What is a satellite assembly?
When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.

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

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

When should you call the garbage collector in .NET?
As a good rule, you should not call the garbage collector. However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. However, this is usually not a good practice.

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

What happens in memory when you Box and Unbox a value-type?
Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack.



Class

A user-defined data structure that groups properties and methods. Class doesn’t occupies memory.


Object
Instance of Class is called object. An object is created in memory using keyword “new”.


Difference between Struct and Class
Struct are Value type and are stored on stack, while Class are Reference type and are stored on heap.
Struct “do not support” inheritance, while class supports inheritance. However struct can implements interface.
Struct should be used when you want to use a small data structure, while Class is better choice for complex data structure.


What is the difference between instantiating structures with and without using the new keyword?
When a structure is instantiated using the new keyword, a constructor (no-argument or custom, if provided) is called which initializes the fields in the structure. When a structure is instantiated without using the new keyword, no constructor is called. Hence, one has to explicitly initialize all the fields of the structure before using it when instantiated without the new keyword.


Encapsulation
Wrapping up of data and function into a single unit is known as Encapsulation.


Properties
Attribute of object is called properties. Eg1:- A car has color as property.

Eg2:

private string m_Color;;


public string Color

{
get

{

return m_Color;

}

set

{

m_Color = value;

}

}


Car Maruti = new Car();

Maruti.Color= “White”;

Console.Write(Maruti.Color);





Isn't it better to make a field public than providing its property with both set { } and get { } block? After all the property will allow the user to both read and modify the field so why not use public field instead? Motivate your answerNot always! Properties are not just to provide access to the fields; rather, they are supposed to provide controlled access to the fields of our class. As the state of the class depends upon the values of its fields, using properties we can assure that no invalid (or unacceptable) value is assigned to the fields.Eg:private int age;


public int Age

{

get

{

return age;

}

set

{

if(value <> 100)

//throw exception

else

age = value;

}

}



this Keyword

Each object has a reference “this” which points to itself.

Two uses of this keyword.

o Can be used to refer to the current object.

o It can also be used by one constructor to explicitly invoke another constructor of the same class.

Eg1:

class Student

{

private string name;

private int age;


Student(string name, int age)

{

this.name = name;

this.age = age;

}

}


Eg2:

class Circle

{

double x,y,radius;


Circle(double x){

this(x,0,1);

}


Circle(double x, double y){

this(x,y,1);

}


Circle(double x, double y, double radius){

this.x = x;

this.y = y;

this.radius = radius;

}


}


Constructor
A constructor is a special method whose task is to initialize the object of its class.
It is special because its name is the same as the class name.
They do not have return types, not even void and therefore they cannot return values.
They cannot be inherited, though a derived class can call the base class constructor.
Constructor is invoked whenever an object of its associated class is created.
Note: There is always atleast one constructor in every class. If you do not write a constructor, C# automatically provides one for you, this is called default constructor. Eg: class A, default constructor is A().




Static Members of the class
Static members belong to the whole class rather than to individual object
Static members are accessed with the name of class rather than reference to objects.

Eg:

class Test

{

public int rollNo;

public int mathsMarks;

public static int totalMathMarks;

}


class TestDemo

{

public static void main()

{

Test stud1 = new Test();

stud1.rollNo = 1;

stud1.mathsMarks = 40;


stud2.rollNo = 2;

stud2.mathsMarks = 43;


Test.totalMathsMarks = stud1.mathsMarks + stud2.mathsMarks;

}

}


Static Method of the class
Methods that you can call directly without first creating an instance of a class. Eg: Main() Method, Console.WriteLine()

You can use static fields, methods, properties and even constructors which will be called before any instance of the class is created.

As static methods may be called without any reference to object, you can not use instance members inside static methods or properties, while you may call a static member from a non-static context. The reason for being able to call static members from non-static context is that static members belong to the class and are present irrespective of the existence of even a single object.



Static Constructor
In C# it is possible to write a static no-parameter constructor for a class. Such a class is executed once, when first object of class is created.

One reason for writing a static constructor would be if your class has some static fields or properties that need to be initialized from an external source before the class is first used.

Eg:

Class MyClass

{

static MyClass()

{

//Initialization Code for static fields and properties.

}

}



Finalize() Method of Object class
Each class in C# is automatically (implicitly) inherited from the Object class which contains a method Finalize(). This method is guaranteed to be called when your object is garbage collected (removed from memory). You can override this method and put here code for freeing resources that you reserved when using the object.

For example

Protected override void Finalize()

{

try

{

Console.WriteLine(“Destructing Object….”);

//put some code here.

}

finally

{

base.Finalize();

}

}


Destructor
A destructor is just opposite to constructor.

It has same as the class name, but with prefix ~ (tilde).

They do not have return types, not even void and therefore they cannot return values.

destructor is invoked whenever an object is about to be garbage collected

Eg:

class person

{

//constructor

person()

{

}


//destructor

~person()

{

//put resource freeing code here.

}

}


What is the difference between the destructor and the Finalize() method? When does the Finalize() method get called?
Finalize() corresponds to the .Net Framework and is part of the System.Object class. Destructors are C#'s implementation of the Finalize() method. The functionality of both Finalize() and the destructor is the same, i.e., they contain code for freeing the resources when the object is about to be garbage collected. In C#, destructors are converted to the Finalize() method when the program is compiled. The Finalize() method is called by the .Net Runtime and we can not predict when it will be called. It is guaranteed to be called when there is no reference pointing to the object and the object is about to be garbage collected.


Garbage Collection
Garbage collection is the mechanism that reclaims the memory resources of an object when it is no longer referenced by a variable.
.Net Runtime performs automatically performs garbage collection, however you can force the garbage collection to run at a certain point in your code by calling System.GC.Collect().
Advantage of Garbage collection : It prevents programming error that could otherwise occur by incorrectly deleting or failing to delete objects.


Enumeration
Enumeration improves code readability. It also helps in avoiding typing mistake.







Concept of Heap and Stack

Local Variables
Stack
Free Memory

(Larger Memory Area than Stack).
Heap

Global Variables
Permanent Storage area

Program Instruction



The Program Instruction and Global and Static variables are stored in a region known as permanent storage area and the local variables are stored in another area called stack. The memory space located between these two regions is available for dynamic memory allocation during execution of program. This free memory region is called heap. The size of heap keeps on changing when program is executed due to creation and death of variables that are local to functions and blocks. Therefore, it is possible to encounter memory “overflow” during dynamic allocation process.





Value Type and Reference Type

A variable is value type or reference type is solely determined by its data type.

Eg: int, float, char, decimal, bool, decimal, struct, etc are value types, while object type such as class, String, Array, etc are reference type.


Value Type
As name suggest Value Type stores “value” directly.

For eg:

//I and J are both of type int

I = 20;

J = I;

int is a value type, which means that the above statements will results in two locations in memory.

For each instance of value type separate memory is allocated.

Stored in a Stack.

It Provides Quick Access, because of value located on stack.


Reference Type
As name suggest Reference Type stores “reference” to the value.

For eg:

Vector X, Y; //Object is defined. (No memory is allocated.)

X = new Vector(); //Memory is allocated to Object. //(new is responsible for allocating memory.)

X.value = 30; //Initialising value field in a vector class.

Y = X; //Both X and Y points to same memory location. //No memory is created for Y.

Console.writeline(Y.value); //displays 30, as both points to same memory

Y.value = 50;

Console.writeline(X.value); //displays 50.

Note: If a variable is reference it is possible to indicate that it does not refer to any object by setting its value to null;

Reference type are stored on Heap.

It provides comparatively slower access, as value located on heap.


ref keyword

Passing variables by value is the default. However, we can force the value parameter to be passed by reference. Note: variable “must” be initialized before it is passed into a method.


out keyword

out keyword is used for passing a variable for output purpose. It has same concept as ref keyword, but passing a ref parameter needs variable to be initialized while out parameter is passed without initialized.

It is useful when we want to return more than one value from the method.

Note: You must assigned value to out parameter in method body, otherwise the method won’t compiled.



Boxing and Un-Boxing
Boxing: means converting value-type to reference-type.

Eg:

int I = 20;

string s = I.ToSting();


UnBoxing: means converting reference-type to value-type.

Eg:

int I = 20;

string s = I.ToString(); //Box the int

int J = Convert.ToInt32(s); //UnBox it back to an int.


Note: Performance Overheads due to boxing and unboxing as the boxing makes a copy of value type from stack and place it inside an object of type System.Object in the heap.


Inheritance
The process of sub-classing a class to extend its functionality is called Inheritance.

It provides idea of reusability.


Order of Constructor execution in Inheritance
constructors are called in the order from the top to the bottom (parent to child class) in inheritance hierarchy.


Order of Destructor execution in Inheritance
The destructors are called in the reverse order, i.e., from the bottom to the top (child to parent class) in the inheritance hierarchy.

What are Sealed Classes in C#?
The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class. (A sealed class cannot also be an abstract class)

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

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.

Fast Facts of Inheritance
Multiple inheritance of classes is not allowed in C#.

In C# you can implements more than one interface, thus multiple inheritance is achieved through interface.

The Object class defined in the System namespace is implicitly the ultimate base class of all the classes in C# (and the .NET framework)

Structures (struct) in C# does not support inheritance, it can only implements interfaces.


Polymorphism
Polymorphism means same operation may behave differently on different classes.

Eg:

Method Overloading is an example of Compile Time Polymorphism.

Method Overriding is an example of Run Time Polymorphism


Does C#.net supports multiple inheritance?

No. A class can inherit from only one base class, however a class can implements many interface, which servers some of the same purpose without increasing complexity.


How many types of Access Modifiers.

1) Public – Allows the members to be globally accessible.

2) Private – Limits the member’s access to only the containing type.

3) Protected – Limits the member’s access to the containing type and all classes derived from the containing type.

4) Internal – Limits the member’s access to within the current project.


Method Overloading
Method with same name but with different arguments is called method overloading.

Method Overloading forms compile-time polymorphism.

Eg:

class A1

{

void hello()

{ Console.WriteLine(“Hello”); }


void hello(string s)

{ Console.WriteLine(“Hello {0}”,s); }

}



Method Overriding
Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass.

Method overriding forms Run-time polymorphism.

Note: By default functions are not virtual in C# and so you need to write “virtual” explicitly. While by default in Java each function are virtual.

Eg1:

Class parent

{

virtual void hello()

{ Console.WriteLine(“Hello from Parent”); }

}


Class child : parent

{

override void hello()

{ Console.WriteLine(“Hello from Child”); }

}


static void main()

{

parent objParent = new child();

objParent.hello();

}

//Output

Hello from Child.


Virtual Method
By declaring base class function as virtual, we allow the function to be overridden in any of derived class.

Eg:

Class parent

{

virtual void hello()

{ Console.WriteLine(“Hello from Parent”); }

}


Class child : parent

{

override void hello()

{ Console.WriteLine(“Hello from Child”); }

}


static void main()

{

parent objParent = new child();

objParent.hello();

}

//Output

Hello from Child.

-------------------------------------------------------------------


Learn Visual C# Programming 
  1. Programming C# for Beginners
  2. Programming XML with C#
  3. GDI+ Tutorial for Beginners
  4. Working with Arrays in .NET
  5. Introduction to Multithreading in C# 
  6. Creating C# Class Library (DLL)
  7. Creating a Windows Service in C#
  8. Exception Handling in C#
  9. Reports using Report Viewer in Visual Studio 2005
  10. Printing in C# and .NET
  11. ASP.NET Quick Start Tutorials
  12. ASP.NET Web Services QuickStart Tutorial 
  13. Data Access and ADO.NET
  14. Common Tasks QuickStart Tutorial     


C# Language   
Windows Forms Controls using C#
  1. DataAdapter in C#
  2. DataGridView Control in C#
  3. DataReader in C#
  4. DataSet in C#
  5. GroupBox in C#
  6. HelpProvider in C#
  7. HScrollBar in C#
  8. ImageList in C#
  9. MaskedTextBox in C#
  10. MenuStrip in C#  
  11. Panel in C# 
  12. PageSetupDialog in C#
  13. PictureBox in C#
  14. PrintDialog in C#
  15. PrintPreviewControl in C#
  16. Process in C#
  17. SerialPort in C#
  18. Tooltip in C#
  19. ToolStrip in C#
  20. TrackBar in C#
  21. TreeView in C#





Search for Type Of Materials