Thursday, February 10, 2011

C# Interview Questions

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.

3. What’s the implicit name of the parameter that gets passed into the class’ set method?
         Value, and it’s datatype depends on whatever variable we’re changing.

4. How do you inherit from a class in C#?
          Place a colon and then the name of the base class.

5. Does C# support multiple inheritance?
           No, use interfaces instead.

6. When you inherit a protected class-level variable, who is it available to?             Classes in the same namespace.

7. Are private class-level variables inherited?
          Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited.

8. Describe the accessibility modifier protected internal.?
          It’s available to derived classes and classes within the same Assembly (and naturally from the base class it’s declared in).

9. C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write?
          Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.

10. How’s method overriding different from overloading?                   When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.

11. Can you override private virtual methods?
             No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.

12. Can you prevent your class from being inherited and becoming a base class for some other classes?               Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It’s the same concept as final class in Java.

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

14. When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)?            When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.

15. What’s an interface class?              It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes.

16. Why can’t you specify the accessibility modifier for methods inside the interface?                  They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it’s public by default.

17. What’s the difference between an interface and abstract class?                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.

18. How can you overload a method?               Different parameter data types, different number of parameters, different order of parameters.

19. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited            constructor to an arbitrary 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.

20. Is it namespace class or class namespace?
             The .NET class library is organized into namespaces. Each namespace contains a functionally related group of classes so natural namespace comes first.

21. Are private class-level variables inherited?
Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.

22. Why does DllImport not work for me?
 All methods marked with the DllImport attribute must be marked as public static extern.

23. Why does my Windows application pop up a console window every time I run it?
Make sure that the target type set in the project properties setting is set to Windows Application, and not Console Application. If you’re using the command line, compile with /target:winexe, not /target:exe.

24. Why do I get an error (CS1006) when trying to declare a method without specifying a return type?
If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following is an example: // This results in a CS1006 error public static staticMethod (mainStatic obj) // This will work as wanted public static void staticMethod (mainStatic obj)

25. Why do I get a syntax error when trying to declare a variable called checked?
 The word checked is a keyword in C#.

26. Why do I get a security exception when I try to run my C# app?
Some security exceptions are thrown if you are working on a network share. There are some parts of the frameworks that will not run if being run off a share (roaming profile, mapped drives, etc.). To see if this is what’s happening, just move the executable over to your local drive and see if it runs without the exceptions. One of the common exceptions thrown under these conditions is System.Security.SecurityException. To get around this, you can change your security policy for the intranet zone, code group 1.2, (the zone that running off shared folders falls into) by using the caspol.exe tool.

27. Why do I get a CS5001: does not have an entry point defined error when compiling?
The most common problem is that you used a lowercase ‘m’ when defining the Main method. The correct way to implement the entry point is as follows: class test { static void Main(string[] args) {} }

28. What optimizations does the C# compiler perform when you use the /optimize+ compiler option?
The following is a response from a developer on the C# compiler team: We get rid of unused locals (i.e., locals that are never read, even if assigned). We get rid of unreachable code. We get rid of try-catch with an empty try. We get rid of try-finally with an empty try. We get rid of try-finally with an empty finally. We optimize branches over branches: gotoif A, lab1 goto lab2: lab1: turns into: gotoif !A, lab2 lab1: We optimize branches to ret, branches to next instruction, and branches to branches.

29. What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname() does not compile)?
 The syntax for calling another constructor is as follows: class B { B(int i) { } } class C : B { C() : base(5) // call base constructor B(5) { } C(int i) : this() // call C() { } public static void Main() {} }

30. What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development?
 Try using RegAsm.exe. Search MSDN on Assembly Registration Tool.

31. What is the difference between a struct and a class in C#?
From language spec: The list of similarities between classes and structs is as follows. Longstructs can implement interfaces and can have the same kinds of members as classes. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.

32. Is there regular expression (regex) support available to C# developers?
Yes. The .NET class libraries provide support for regular expressions. Look at the System.Text.RegularExpressions namespace.

33. Is there any sample C# code for simple threading?
Yes:
1.  using System;
2.  using System.Threading;
3.  class ThreadTest
4.  {
5.    public void runme()
6.    {
7.           Console.WriteLine("Runme Called");
8.    }
9.    public static void Main(String[] args)
10.  {
11.         ThreadTest b = new ThreadTest();
12.         Thread t = new Thread(new ThreadStart(b.runme));
13.         t.Start();
14.  }
}
34. Is there an equivalent of exit() for quitting a C# .NET application?
 Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it’s a Windows Forms app.

35. Is there a way to force garbage collection?
            Yes. Set all references to null and then call System.GC.Collect(). If you need to have some objects destructed, and System.GC.Collect() doesn’t seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers().

36. Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace?
              There is no way to restrict to a namespace. Namespaces are never units of protection. But if you’re using assemblies, you can use the ‘internal’ access modifier to restrict access to only within the assembly.

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

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

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

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

41. What’s class SortedList underneath?
A sorted HashTable.

42. Will finally block get executed if the exception had not occurred?
Yes.
43. 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 {}.

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

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

46. How do I declare inout arguments in C#?
The equivalent of inout in C# is ref. , as shown in the following
example: public void MyMethod (ref String str1, out String str2)
{
...
}
When calling the method, it would be called like this: String s1;
String s2;
s1 = "Hello";
MyMethod(ref s1, out s2);
Console.WriteLine(s1);
Console.WriteLine(s2);
Notice that you need to specify ref when declaring the function and calling it.

47. How do I  make a dll in C#?
Open the property page of the Project File and then
open CommonProperties -> Genaral ->Output Type
change the output type to class library and build the application then u'll get a dll file.
also in the Configuartion Properties ->Build -> Output Path
u mention the path where u wnat to store your dll file.

48. How do I register my code for use by classic COM clients?
               Use the regasm.exe utility to generate a type library (if needed) and the necessary entries in the Windows Registry to make a class available to classic COM clients. Once a class is registered in the Windows Registry with regasm.exe, a COM client can use the class as though it were a COM class.
49. Describe the difference between a Thread and a Process?              Threads are similar to processes, but differ in the way that they share resources. Threads are distinguished from processes in that processes are typically independent, carry considerable state information and have separate address spaces. Threads typically share the memory belonging to their parent process.
50. What is the difference between an EXE and a DLL?            An exe runs in it's own address space / process but Dll gets loaded into the exe's process address space.

51. What is CLR?
              
As part of Microsoft's .NET Framework, the Common Language Runtime (CLR) is programming that manages the execution of programs written in any of several supported languages, allowing them to share common object-oriented classes written in any of the languages.

52. What are Namespaces?
             Logical Container, which will organize your classes, is called namespaces.

53. What is boxing?
               Conversion of a value type to a reference type is called Boxing. The vice versa is called UnBoxing. Boxing is implicit conversion. Unboxing is Explicit conversion.

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

55. Can you store multiple  data types in System.Array?
         No.
 
56. How can you sort the elements of the array in descending order?
           By calling Sort() and then Reverse() methods.

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

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

59. Can you declare the override method static while the original method is non-static?
           No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

60. What's the implicit name of the parameter that gets passed into the class' set method?
               Value :parameter gets passed into the class' set method

61. Is it mandatory to implement all the methods which are there in abstract class if we inherit that abstract class..?
               No only function marked as abstract shoud be implemented.the following code runs fine abstract public class baseclass { public abstract void method1(); public void method2(){Console.WriteLine("Base Method 2");} } public class derivedclass:baseclass { public override void method1(){Console.WriteLine("Derived Method 1");} //public override void method2(){Console.WriteLine("Derived Method 1");;} }

62. What is CLS?
           Common Language Specification. The Common Language Specification (CLS) describes a set of features that different languages have in common.
The CLS includes a subset of the Common Type System (CTS).

63. What is Reflection?            Used to Get assembly metadata using code. To organize the assemblies at runtime we use System.Reflection name space. To Load,to get the information about the assemblies at runtime according to need this can be done using System.Reflection.

64. What is the use of fixed statement?
               The fixed statement sets a pointer to a managed variable and "pins" that variable during the execution of statement. Without fixed, pointers to managed variables would be of little use since garbage collection could relocate the variables unpredictably. (In fact, the C# compiler will not allow you to set a pointer to a managed variable except in a fixed statement.)

Eg: Class A { public int i; }

A objA = new A; // A is a .net managed type

fixed(int *pt = &objA.i) // use fixed while using pointers with managed

// variables

{

*pt=45; // in this block use the pointer the way u want

}

65. What is wrapper class?is it available in c#?
               Wrapper Classes are the classes that wrap up the primitive values in to a class that offer utility method to access it . For eg you can store list of int values in a vector class and access the class. Also the methods are static and hence you can use them without creating an instance . The values are immutable .

66. What is the difference between shadow and override?
               Overriding is used to redefines only the methods.but shadowing redefines the entire element.
In case of Shadow : TO access the Base/Parent class elements use the MyBase Keyword
In case of Overriding : TO access the Base/Parent class elements use the Me Keyword

67. Is it possible to have different access modifiers on the get/set methods of a property?
          No. The access modifier on a property applies to both its get and set accessors. What you need to do if you want them to be different is make the property read-only (by only providing a get accessor) and create a private/internal set method that is separate from the property.

68. How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#?
           You want the lock statement, which is the same as Monitor Enter/Exit:
lock(obj) { // code }
      translates to
try {
        CriticalSection.Enter(obj);
        // code
}
finally
{
        CriticalSection.Exit(obj);
}
69. 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.

70. What do you know about .NET assemblies?
       Assemblies are the smallest units of versioning and deployment in the .NET application. Assemblies are also the building blocks for programs such as Web services, Windows services, serviced components, and .NET remoting applications.

71. What’s the difference between private and shared assembly?
Private assembly is used inside an application only and does not have to be identified by a strong name. Shared assembly can be used by multiple applications and has to have a strong name.
72. What’s a strong name?
A strong name includes the name of the assembly, version number, culture identity, and a public key token.

73. Can you prevent your class from being inherited and becoming a base class for some other classes?
Yes, that is what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It is the same concept as final class in Java.

74. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary 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.
75. Is it possible to inline assembly or IL in C# code?
        
 No.

No comments:

Post a Comment