Interview Questions for C#

We do not guarantee the correctness of all answers. It is user’s responsibility to make sure that the answers are right. Good luck.

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

2. Describe the accessibility modifier “protected internal”.

    It is available to classes that are within the same assembly and derived from the specified base class.

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

4. 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.
An object qualifies as being called immutable if its value cannot be modified once it has been created. For example, methods that appear to modify a String actually return a new String containing the modification. Developers are modifying strings all the time in their code. This may appear to the developer as mutable - but it is not. What actually happens is your string variable/object has been changed to reference a new string value containing the results of your new string value. For this very reason .NET has the System.Text.StringBuilder class. If you find it necessary to modify the actual contents of a string-like object heavily, such as in a for or foreach loop, use the System.Text.StringBuilder class.

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

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

    NO.

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

8. How can you sort the elements of the array in descending order?

    By calling Sort() and then Reverse() methods.

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

    HashTable.

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

    Yes.

11. What’s the C# syntax to catch any possible exception?

   
catch{
//Statements on exception
}

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

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

14. Can you prevent your class from being inherited by another class?

    Yes. The keyword “sealed” will prevent the class from being inherited.

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

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

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

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

19. Why can’t you specify the accessibility modifier for methods inside the interface?

    They all must be public, and are therefore public by default.

20. Can you inherit multiple interfaces?

    Yes..NET does support multiple interfaces. (but does not suport fro classess).

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

22. 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.
When creating a specialized class only one class can be implemented, but may interfaces can be extended. Also if you are adding new methods to an interface the code will break in the specialized class, unless modify the code in the specialized class. But if you have an abstract class, you can add a virtual method can be added without affecting the specialized class codes.

23. 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. Structs can't have distructor. Another difference is that structs cannot inherit.

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

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

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

27. What are the different ways a method can be overloaded?

    Different parameter data types, different number of parameters, different order of parameters.

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

29. What’s a delegate?

    A delegate object encapsulates a reference to a method.

30. What’s a multicast delegate?

    A delegate that has multiple handlers assigned to it.

31. Is XML case-sensitive?

    Yes.

32. What’s the difference between // comments, /* */ comments and /// comments?

    Single-line comments, multi-line comments, and XML documentation comments.

33. How do you generate documentation from the C# file commented properly with a command-line compiler?

    Compile it with the /doc switch.

34. What debugging tools come with the .NET SDK?

    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.

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

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

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

38. Where is the output of TextWriterTraceListener redirected?

    Where is the output of TextWriterTraceListener redirected?.

39. How do you debug an ASP.NET Web application?

    Attach the aspnet_wp.exe process to the DbgClr debugger.

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

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

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

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

44. What is the wildcard character in SQL?

    "%"

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

46. What connections does Microsoft SQL Server support?

    Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password).

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

48. What does the Initial Catalog parameter define in the connection string?

    The database name to connect to.

49. What does the Dispose method do with the connection object?

    Deletes it from the memory.

50. 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. Explicitly close connection with the "Close()'.

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

52. What are the ways to deploy an assembly?

    An MSI installer, a CAB archive, and XCOPY command.

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

54. What namespaces are necessary to create a localized application?

    System.Globalization and System.Resources.

55. What is the smallest unit of execution in .NET?

    an Assembly.

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

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

    Boxing.

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

59. Can you explain what inheritance is and an example of when you might use it?

    When you want to inherit (use the functionality of) another class.

60. Whats an assembly?

    Assemblies are the building blocks of the .NET framework.

61. How can you retrieve the data stored in session state upon server crash?

    By default the session state is stored in process. But if can save the session state in windows service or in a database table it is possible to retrieve the data stored in session state.

62. Which class is responsible for output caching?

    HttpCachePolicy.

63. What is Runtime Type Identification(RTTI) in C#?

    RTTI allows the type of an object to determined during program execution.This test can be used to discover precisely what type of object being reffered to by a base class reference. Another use of RTTI is to test in advance whether cast will succeed.

64. Which keyword is used to detemine if an object is of a certain type?

    "is".

65. Which keyword is used to try a cast at run time with out rise an exception?

    "as".
If cast succeeds, then a reference to the type is returned. Otherwose a null reference is returned.

66. In C# how can you get information about an object type?

    Use "typeof" operator.

67. Which is the return type of "typeof" operator?

    System.Type

68. Which is the base clss of System .Type?

    "System.Reflection.MemberInfo".

69. Explain some reflection techniques?

   

  • Obtain information about methods.
  • Invoking methods.
  • Constructing objects.
  • loading types fromassemblies.

  • 70. What is the return type of "MethodInfo.Invoke()" ?

        The value returned by the invoked method.

    71. Explain Attributes in c#?

        It allow to add declarative information to a program. Attributes are not a member of a class, but it species the suplimental information that is attached to an item.

    72. All attribute class must be a cub class of ____.

        System.Attribute

    73. What are the use of new Keywords in c#?

        1. To create an Object from a class.
    To Hide a member from a base class in an inherited class.

    74. What are the use of using statement?

        1. Import directives
    2. Automatic release of an object.

    75. How Can you achive multiple inheritance in c#?

        Use interfaces for multiple inheritance.

    76. Diffrenve betwen 'const' and 'readonly' variables?

        The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants.
    const

  • Can't be static.
  • Value is evaluated at compile time.
  • Initiailized at declaration only.
    readonly
  • Can be either instance-level or static.
  • Value is evaluated at run time.
  • Can be initialized in declaration or by code in the constructor.

  • 77. Can we pass variable number of parameters into a function ?

        Yes.
    by using the keyword params.
    public void displayVals(params int[] intvals)

    78. What’s a strong name?

        A strong name includes the name of the assembly, version number, culture identity, and a public key token.

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

        a == b is used to compare the references of two objects.
    a.Equals(b) is used to compare two objects .

    80. What is strong-typing versus weak-typing? Which is preferred? Why?

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

    81. What is the difference between an EXE and a DLL?

        exe file is a excutable file which runs in a seperate process which is managed by OS,where as a dll file is a dynamic link library which can be used in exe files and other dll files.

    82. Describe the difference between a Thread and a Process?

        A process will execute the threads(set of instructions), which may contain multiple threads sometimes. THREAD It contains a group of instructions that a processor has to do.
    A Process has its own memory space, runtime enivorment and process ID.A Thread run inside a Process and shares its resources with other threads.

    83. What is the signature of a delegate?

        Public delegate return_type delegate_name ([Object obj1][, Object obj2]..);

    84. In C#, every attribute must have at least one of the following?

        Constructor*

    85. In C#, you derive new, custom attribute classes from which of the following?

        System.Attribute

    86. What is metadata?

        Metadata is the information stored in the assembly that describes the type and methods of the assembly and provides other usefull information about the assembly. Assemblies are said to be self describing because of the metadata.

    87. What is modules in .Net?

        Modules are the constituent piece of assemblies. Standing alone modules can't be executed. They must be combined into assemblies to be useful.

    88. What is Reflection?

        Reflection is a process by which a programme can read it's own metadata 0r metadata from another program.

    89. What is partial class?

        .NET 2.0 supports partial classes. It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled.During compile time, it simply groups all the various partial classes and treats them as a single entity.
    Partial class allows a clean separation of business logic and the user interface.
    If any of the parts are declared abstract, then the entire type is considered abstract. If any of the parts are declared sealed, then the entire type is considered sealed. If any of the parts declare a base type, then the entire type inherits that class.Partial classes will also make debugging easier, as the code is partitioned into separate files. When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously. To split a class definition, use the keyword modifier partial.

    90. What isshared assemblies?

        private assemblies are intented to use for many application.
    1.)Shared assemblies must have a stron name.Strong names are globaly unique.
    2.) Sahred assemblies must protected aganist newer versions trampling over it, and so each version you release must have a new version number
    3.) Shared assemblies must placed in the Global Assembly Cache(GAC).

    91. What is private assemblies?

        private assemblies are intented to use only for one application.

    92. What are the diffrent assemblies?

        private and shared assemblies.

    93. What is probing?

        The process of loading an assembly into it's application by the assembly resolver is called probing.

    94. Is it possible to "Switch" on a string( switch(Switch value)
    case:
    ....}

        Ye, it is

    95. What is the use of "is" operator in c#?

        The "is" operator evaluates true, if the expression can safely type cast to type without throwing an exception. The syntax is
    expression is type

    96. What is the use of "as" operator in c#?

        The "as" operator combines the “is” and cast operator by testing the first to see whether a cast is valid and then completing the castwhen it is. If the cast is not valid the operator returns null The syntax is
    expression as type

    97. c# array are reference type. True or False

        True.

    98. What Are C# Generics?

        Generic is a code template that can be applied to use the same code repeatedly. Each time the generic is used, it can be customized for different data types without needing to rewrite any of the internal code. Version 2.0 of the .NET Framework introduces a new namespace viz. System.Collections.Generic, which contains the classes that support Generics.

    99. What is the use of "param" keyword in c#?

        The params keyword allows you to pass in a variable number of parameters without nessarily explicitly creating the array.

    100. How to declare a "multi dimensional array in c#?

        // declare a 4x3 integer array
    int[,] rectangularArray = new int[rows, columns];

    101. Explain Jagged arrays in c#?

        A jagged array is an array of arrays. It is called jagged because each row need not be the same size as all others, and thus a graphical representation of the arry would not be square. It can be declared as

    // declare the jagged array as 4 rows high
    int[ ][ ] jaggedArray = new int[4][ ];

    102. What is c# indexers?

        An indexer is a C# construct that allows you to access collections contained by class using the [ ] syntax of arrays.

    103. What is the use of Keyword "yield"in C#?

        Used in an iterator block to provide a value to the enumerator object or to signal the end of iteration. It takes one of the following forms:

    yield return expression;
    yield break;

    104. How can we create specilized class from System.String?

        It not possible to create child classes from System.String, because System.String is a sealed class.

    105. Which is the Namespace for "Regular Expressions"?

        System.Text.RegularExpressions

    106. Whic is the base class for Exception?

        System.Exception

    107. Which is the base class used to derive custom exception?

        System.ApplicationException

    108. What is C# deligates?

        Deligates are referece type used to encapsulate a method with specific signature and return type. The deligate can be used to invoke that encapsulated method.

    109. What is Regression testing?

        Regression testing is any type of software testing that seeks to uncover new software bugs, or regressions, in existing functional and non-functional areas of a system after changes, such as enhancements, patches or configuration changes, have been made to them.

    110. What is Lambda Expressions for LINQ

        A lambda expression is an anonymous function that can contain expressions and statements, and you can use it to create delegates or expression tree types.

    111. What’s the implicit name of the parameter that gets passed into the class set method?

        Value, and its datatype depends on whatever variable we’re changing.

    112. How do you inherit from a class in C#?

        Place a colon and then the name of the base class. Notice that it’s double-colon in C++.

    113. Who is a protected class-level variable available to?

        It is available to any sub-class (a class inheriting this class).

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

    115. Describe the accessibility modifier “protected internal".

        It is available to classes that are within the same assembly and derived from the specified base class

    116. What is an "object" ?

        Object is an instance of the class.

    117. What is the meaning of "private" modifier to the members of a class?

        "Private" members are accessible only within the body of the class or the struct in which they are declared.

    118. What is the meaning of "public" modifier to the members of a class?

        "public" means the the members of the class is accessible to any methods of classes in any package. There are no restrictions on accessing public members.

    119. What is the meaning of "protected" modifier to the members of a class?

        A "protected" member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.

    120. What is the meaning of "internal" modifier to the members of a class?

        Internal members are accessible only within files in the same assembly.

    121. What is the meaning of "protected internal" modifier to the members of a class?

        "protected internal" meembers are acceessible to methods of the container calss, methods of the class derived from this class and also any class in the same assembly.

    122. Expalin the access modifiers using in c#?

       

     privateprotectdinternalprotectd internalpublic
    Same ClassYesYesYesYesYes
    Same package Non Sub ClassNoNoYesYesYes
    Same Package Inherited classNoYesYesYesYes
    Diffrent Package Non Sub ClassNoNoNoNoYes
    Diffrent Package inherited ClassNoYesNoYesYes

    123. What is the default accessmodifier for a class?

        Internal.

    124. What is the default accessmodifier for attributes or members of a class?

        private.

    125. What is the default accessmodifier for a packages?

        public.

    126. In .Net Framework which is the class suporting the concept of copy constructor?

        ICloneable

    127. What is the use of "this" keyword?

        "this" keyword reffers to the instance of current object.

    128. What is static class members?

        Static membersa are associated with the class only. Not with the instance of the class.

    129. Is it possible to access the static memebrs thru the instance of a class?

        No.

    130. Whether Static data can accees thru the instance of the Class?

        Yes.

    131. Is it posible for a static function can access non static members of the class?

        No.

    132. Whether static constructor is allowed in c#?

        Yes

    133. Is it posible to inherit "static"classess?

        No.

    134. When the class destructor is called?

        When the object is distroyed.

    135. What is the signature of the distructor?

        ~ Class-Name(){//statements}

    136. How can you pass more than one value from a function?

        Useing passing parameter by reference method.
    "public void GetTime(ref int h, ref int m, ref int s){}" and call "t. GetTime(ref int h, ref int m, ref int s)"

    137. How can you pass un initialized values to methods?

        Use "out" Key word for the parameter.

    138. How can overload methods in c# ?

        A method can be overloaded by using " diffrent number or Types of parameters"

    139. Is oeprator overloading is allowed in c#?

        Yes.

    140. What is the use of "virtual" keyword in methods?

        "virtual" keyword in methods means this method can be override in inherited class.

    141. What is the use of "override" keyword in methods?

        "override" keyword in methods means this method is an override version of base class.

    142. What is the use of "new" keyword in methods?

        "new" keyword in methods means this method is NOT an override version of base class.

    143. Consider class
    public class foo{   int age;
     public foo(int age){
      this.age=age;
     }
    }

    Is this class able to call a default constructor(foo f = new foo())

        No. Once you supplied a constructor class can't call it's default constructor.

    144. Whether classes can inherit constructor?

        No.

    145. What is an abstract method?

        abstract method is one without implementation. Thei method is implementing in it's spelized class. A class with an abstract method should be also abstract.

    146. How can be prevent inheritance?

        Using keyword sealed.

    147. Which is the root(base class) of all C# classess?

        System.Object

    148. What do you mean by boxing and unboxing in C#?

        Boxing and un boxing are the value types to be treated as reference types and vice versa.

    149. What is Polymorphism

        Polimorphism is a feature that allows one interface for many actions.

    150. What is the structure of a class?

        [attributes] [access-modifiers] class identifier [ : base class] { class Body}

    151. What is the purpose of access modifiers in OOPs?

        Accessmodifiers controls the accessibility (scope and visibility) of data methods and class.

    152. What is the signature of a class constructor?

        [access-modifier] Class-name([arguments]){}

    153. If a class has no constructior, How the object is construcred?

        CLR will provide the default constructor.

    154. What are default values for the member data at the time of creation of an object?

        Numeric --> 0
    bool --> false
    char --> \0 (null)
    enum -->0
    reffrence -->null

    155. True OR false
    Unboxing is implicit in C#?

        False.

    156. which is the key word using to implement operator Overloading?

        operator

    157. What is the diffrence between structs and classes?

        Struct is a value tye and class is a reference type.
    structs dosen't suport inheritance or desctructors.

    158. What is delegates ?

        They are reference type used to encapsulate a method with a specic signature and type.

    159. What is Encapsulation?

        Encapsulation is the mechanism that binds toughter code and the data it manipulate and keeps both safe from outside inheritance and misuse.

    160. What is the keyword "private" for data and method means?

        The private methods and data of a class is ONLY accessed by the code that is a member of the class.

    161. What is the difference between .Net Assembly and Namespace?

        Assemblies are the building blocks of .NET Framework applications; An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly.

    A namespace, on the other hand is a collection of classes. It’s more used for logical organization of your classes. Namespaces are a way of grouping type names and reducing the chance of name collisions.

    162. What is Assembly Manifest?

        Every assembly contains an assembly manifest, a set of metadata with information about the assembly. The assembly manifest contains these items:

      The assembly name and version
      The culture or language the assembly supports (not required in all assemblies)
      The public key for any strong name assigned to the assembly (not required in all assemblies)
      A list of files in the assembly with hash information
      Information on exported types
      Information on referenced assemblies

    163. What is the signature of a deligate?

        public delegate Return Type Method_Name([[Type var],[Type var]]);

    164. Waht is the return type of a constructor?

        There is NO return type for a constructor.

    165. True OR false
    Boxing is implicit in C#?

        True.

    166. Whether optional arguments are allowed in c#?

        Yes. Named and Optional Arguments are allowed in c#.

    167. What is constructors?

        Constructot initilizes an object immediatly upon creation.

    168. Any three properties of Object oriented design?

        Encapsulation, Inheritance, Polimorphism.

    169. Which are the access modifiers using in c#?

        public, private, protected, internal, Protectd internal.

    170. What is inheritance?

        Inheritance is the process by which one objects acquires the properties of another object.

    171. Does C# support multiple-inheritance?

        No.

    172. What is the use of Finalize Method in C#?

        the Finalize Method allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.

    Tags: Interview Questions for C#
    Updated on: November 2024