Card Set Information

2012-06-19 17:40:03
interview csharp dotnet

C# interview questions (part 4)
Show Answers:

  1. What is boxing?
    • Encapsulating a copy of a value type in an object.
    • CLR wraps the value inside a System.Object and stores it on the managed heap.

    • int i =123;
    • // The following line boxes i.
    • object o = i;
  2. What is unboxing?
    Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit.

    • object o = 123;
    • i = (int)o; // unboxing
  3. What is Thread Synchronization? (info)
    In a multithreaded environment, each thread has its own local thread stack and registers. If multiple threads access the same resource for read and write, the value may not be the correct value. For example, let's say our application contains two threads, one thread for reading content from the file and another thread writing the content to the file. If the write thread tries to write and the read thread tries to read the same data, the data might become corrupted. In this situation, we want to lock the file access. The thread synchronization has two stages. Signaled and non-signaled.The signaled state allows objects to access and modify data. The non-signaled state does allow accessing or modifying the data in the thread local stack.
  4. Thread Synchronization methods
    • on different processes: Event, Mutex, Semaphore.
    • in same process: Critical Section
  5. Thread Synchronization - Event
    Event is a thread synchronization object used to set the signaled or non-signaled state. The signaled state may be manual or automatic depending on the event declaration.
  6. Thread Synchronization - Mutex
    Mutex is the thread synchronization object which allows to access the resource only one thread at a time. Only when a process goes to the signaled state are the other resources allowed to access.

    A mutex is similar to a monitor; it prevents the simultaneous execution of a block of code by more than one thread at a time. In fact, the name "mutex" is a shortened form of the term "mutually exclusive." Unlike monitors, however, a mutex can be used to synchronize threads across processes. A mutex is represented by the Mutex class.When used for inter-process synchronization, a mutex is called a named mutex because it is to be used in another application, and therefore it cannot be shared by means of a global or static variable. It must be given a name so that both applications can access the same mutex object.Although a mutex can be used for intra-process thread synchronization, using Monitor is generally preferred, because monitors were designed specifically for the .NET Framework and therefore make better use of resources. In contrast, the Mutex class is a wrapper to a Win32 construct. While it is more powerful than a monitor, a mutex requires interop transitions that are more computationally expensive than those required by the Monitor class.
  7. Thread Synchronization - Semaphore
    Semaphore is a thread synchronization object that allows zero to any number of threads access simultaneously.
  8. Thread Synchronization - Critical Section
    The critical section is a thread synchronization object. The other synchronization objects like semaphore, event, and mutex are used to synchronize the resource with different processes. The Critical Section allows synchronization within the same process.
  9. Thread Synchronization - lock
    The lock (C#) and SyncLock (Visual Basic) statements can be used to ensure that a block of code runs to completion without interruption by other threads. This is accomplished by obtaining a mutual-exclusion lock for a given object for the duration of the code block.

    • object lockThis = new object();
    • lock (lockThis)
    • {
    • // Access thread-sensitive resources.
    • }
  10. Thread Synchronization - lock vs Monitor
    lock (x) { DoSomething(); }

    // same as

    • object obj = (object)x;
    • System.Threading.Monitor.Enter(obj);

    • try { DoSomething(); }
    • finally { System.Threading.Monitor.Exit(obj); }
  11. Thread Synchronization - Deadlocks
    Thread synchronization is invaluable in multithreaded applications, but there is always the danger of creating a deadlock, where multiple threads are waiting for each other and the application comes to a halt. A deadlock is analogous to a situation in which cars are stopped at a four-way stop and each person is waiting for the other to go. Avoiding deadlocks is important; the key is careful planning. You can often predict deadlock situations by diagramming multithreaded applications before you start coding.
  12. Thread Synchronization - Thread Pool
    Thread pooling is a form of multithreading in which tasks are added to a queue and automatically started when threads are created.
  13. Thread Synchronization - Monitor
    Monitor objects expose the ability to synchronize access to a region of code by taking and releasing a lock on a particular object using the Monitor.Enter, Monitor.TryEnter, and Monitor.Exit methods. Once you have a lock on a code region, you can use the Monitor.Wait, Monitor.Pulse, and Monitor.PulseAll methods. Wait releases the lock if it is held and waits to be notified. When Wait is notified, it returns and obtains the lock again. Both Pulse and PulseAll signal for the next thread in the wait queue to proceed.

    C# lock statements use Monitor.Enter to take the lock and Monitor.Exit to release it. The advantage of using the language statements is that everything in the lock orSyncLock block is included in a Try statement. The Try statement has a Finally block to guarantee that the lock is released.Monitor locks objects (that is, reference types), not value types. While you can pass a value type to Enter and Exit, it is boxed separately for each call. Since each call creates a separate object, Enternever blocks, and the code it is supposedly protecting is not really synchronized. In addition, the object passed to Exit is different from the object passed to Enter, so Monitor throwsSynchronizationLockException with the message "Object synchronization method was called from an unsynchronized block of code."
  14. 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.
  15. How does assembly versioning in .NET prevent DLL Hell?
    • .NET allows assemblies to specify the name AND the
    • version of any assemblies they need to run.

    Versioning is done only on assemblies with strong names.

    All versioning of assemblies that use the common language runtime is done at the assembly level. The specific version of an assembly and the versions of dependent assemblies are recorded in the assembly's manifest. The default version policy for the runtime is that applications run only with the versions they were built and tested with, unless overridden by explicit version policy in configuration files (the application configuration file, the publisher policy file, and the computer's administrator configuration file).
  16. Assembly Version Number
    Each assembly has a version number as part of its identity. As such, two assemblies that differ by version number are considered by the runtime to be completely different assemblies. This version number is physically represented as a four-part string with the following format:

    <major version>.<minor version>.<build number>.<revision>
  17. Access Modifiers
    public - [for types and type members]. Public access is the most permissive access level. There are no restrictions on accessing public members.

    protected - [member]. 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.

    internal - [types and type members]. Internal members are accessible only within files in the same assembly.

    private - [member]. Private access is the least permissive access level. Private members are accessible only within the body of the class or the struct in which they are declared.
  18. Object-oriented programming
    programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction, encapsulation, messaging, modularity, polymorphism, and inheritance.
  19. OOP - Encapsulation
    • encapsulation means that a group of related properties, methods, and other members are treated as a single unit or object.
    • encapsulation is an attribute of object design. It means that all of the object's data is contained and hidden in the object and access to it restricted to members of that class.
  20. OOP - Inheritance
    • ability to create new classes based on an existing class.
    • Classes can inherit from another class. This is accomplished by putting a colon after the class name when declaring the class, and naming the class to inherit from—the base class—after the colon, as follows:

    • public class A
    • {
    • public A() { }
    • }

    • public class B : A
    • {
    • public B() { }
    • }
    • The new class—the derived class—then gains all the non-private data and behavior of the base class in addition to any other data or behaviors it defines for itself. The new class then has two effective types: the type of the new class and the type of the class it inherits.
  21. OOP - Polymorphism
    • you can have multiple classes that can be used interchangeably, even though each class implements the same properties or methods in different ways.
    • Through inheritance, a class can be used as more than one type; it can be used as its own type, any base types, or any interface type if it implements interfaces. This is called polymorphism. In C#, every type is polymorphic.
  22. OOP - Abstraction
    Abstraction is concerned with hiding, or providing detail at a later date.

    Abstraction is the concept of taking a specific, detailed problem and creating a more general abstract solution. The main idea is that if you abstract away the details then your solution will be more flexible. "abstraction" and "abstract" are different. An abstraction is a generalization, something that has very little dependencies or is very loosely coupled.

    An abstract class is one that isn't fully implemented, it's meant only to be derived from and to have its abstract methods overridden.
  23. abstract (C#) modifier
    The abstract modifier indicates that the thing being modified has a missing or incomplete implementation. The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.
  24. Abstarct class features
    • * An abstract class cannot be instantiated.
    • * An abstract class may contain abstract methods and accessors.
    • * It is not possible to modify an abstract class with the sealed (C# Reference) modifier because the two modifers have opposite meanings. The sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited.
    • * A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.

    It is an error to use the static or virtual modifiers in an abstract method declaration.
  25. Abstract methods features
    • * An abstract method is implicitly a virtual method.
    • * Abstract method declarations are only permitted in abstract classes.
    • * Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no curly braces ({ }) following the signature

    public abstract void MyMethod();

    • The implementation is provided by an overriding method override, which is a member of a non-abstract class.
    • It is an error to use the static or virtual modifiers in an abstract method declaration.
  26. Abstract properties features
    • behave like abstract methods, except for the differences in declaration and invocation syntax.It is an error to use the abstract modifier on a static property.
    • An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
  27. Abstract Class versus Interface
    • An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.
    • An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.
  28. What’s a strong name?
    • A strong name (SN) includes the name of the assembly, version
    • number, culture identity, and a public key token.

    Strong Name is a technology based on cryptographic principles, primary digital signatures. SNs can be used in Versioning, Authentication.
  29. SN (strong name) - Versioning
    Versioning solves known problem called as "DLL hell". Signed assemblies are unique and SN solves problem with namespace collisions (developers can distribute their assemblies even with the same file names as shown of figure below). Assemblies signed with SNs are uniquely identified and are protected and stored in different spaces.
  30. SN (strong name) - Authentication
    The second important feature of Strong Names is authentication; a process where we want to ensure ourselves about the code's origin. This can be used in many situations, such as assigning higher permissions for chosen publishers (as will be shown later) or ensuring that code is provided by a specific supplier.It has been shown that signatures and public keys can be easily removed from assemblies. Yes, that is right but it is correct behavior even when we use digital signatures in emails or anywhere else!
  31. Where are shared assemblies stored?
    Global assembly cache. (GAC)
  32. How can you create a strong name for a .NET assembly?
    With the help of Strong Name tool (sn.exe).
  33. Where’s global assembly cache located on the system?
    Usually C:\winnt\assembly or C:\windows\assembly.
  34. Can you have two files with the same file name in GAC?
    Yes, remember that GAC is a very special folder, and while normally you would not be able to place two files with the same name into a Windows folder, GAC differentiates by version number as well, so it’s possible for MyApp.dll and MyApp.dll to co-exist in GAC if the first one is version and the second one is
  35. 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.
  36. 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.
  37. 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().
  38. Overriding vs Overloading
    Overriding means having a different implementation of the same method in the inherited class. These two methods would have the same signature, but different implementation. One of these would exist in the base class and another in the derived class. These cannot exist in the same class. See also virtual and new...

    Overloading simply involves two or more methods with the same name but different signatures in the same scope
  39. Virtual modifier and "new" keyword
    virtual requires overriding. if non-virtual, can be overriden with "new":

    • class A {
    • public void F() { Console.WriteLine("A.F - non virtual"); }
    • public virtual void G() { Console.WriteLine("A.G - virtual"); }
    • }
    • class B: A {
    • new public void F() { Console.WriteLine("B.F"); }
    • public override void G() { Console.WriteLine("B.G"); }
    • }
  40. When do you absolutely have to declare a class as abstract?
    • 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.
  41. How to implement a trace and assert?
    Use a conditional attribute on the method:

    • using System; using System.Diagnostics;
    • class Debug
    • {
    • [Conditional("TRACE")]
    • public static void Trace(string s) { Console.WriteLine(s); }
    • }
    • class MyClass
    • {
    • public static void Main() { Debug.Trace("hello"); }
    • }

    In this example, the call to Debug.Trace() is made only if the preprocessor symbol TRACE [project properties/build tab, define TRACE constant checked] is defined at the call site. You can define preprocessor symbols on the command line by using the /D switch. The restriction on conditional methods is that they must have void return type.
  42. Explain ACID
    • 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 hasnot),
    • 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).
  43. declare inout arguments
    • public void MyMethod (ref string str1, out string str2)
    • { ... }

    • public void SampleCall()
    • {
    • string str1 = "in param sample";
    • string str2;
    • MyMethod(ref s1, out s2);
    • }
  44. Difference between const and static read-only
    static read-only can be modified by the containing class, but const can never be modified and must be initialized to a compile time constant.

    • To expand on the static read-only case a bit, the containing class can only modify it:
    • -- in the variable declaration (through a variable initializer).
    • -- in the static constructor (instance constructors if it's not static).
  45. Difference between String and 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.

    • You can never actually change the contents of a string, at least with safe code which doesn't use reflection.
    • Because of this, you often end up changing the value of a string variable. For instance, the code s = s.Replace ("foo", "bar"); doesn't change the contents of the string that s originally referred to - it just sets the value of s to a new string, which is a copy of the old string but with "foo" replaced by "bar".
  46. What is the top .NET class that everything is derived from?
  47. 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
  48. Which one is trusted and which one is untrusted?
    - Windows Authentication
    - SQL Server authentication
    • Windows Authentication is trusted because the username and password are checked with the Active Directory
    • SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction
  49. What namespaces are necessary to create a localized application?
    System.Globalization, System.Resources.
  50. 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 is being operated on, a new instance is created.
  51. sample C# code for simple threading?
    using System.Threading;

    • class ThreadTest
    • {
    • public void runme() {Console.WriteLine("Runme Called"); }
    • public static void Main(String[] args)
    • {
    • ThreadTest b = new ThreadTest();
    • Thread t = new Thread(new ThreadStart(runme));
    • t.Start();
    • }
    • }
  52. 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).
  53. Describe the accessibility modifier protected internal
    It is available to derived classes and classes within the same Assembly (and naturally from the base class it is declared in).
  54. What is a multicast delegate?
    It is a delegate that points to and eventually fires off several methods.
  55. 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.
  56. How do you directly call a native function exported from a DLL?
    using DllImport :

    • [DllImport("user32.dll")]
    • public static extern int MessageBoxA(int h, string m, string c, int type);

    • public static int Main()
    • {
    • return MessageBoxA(0, "Hello World!", "Caption", 0);
    • }
  57. What is the .NET datatype that allows the retrieval of data by a unique key?
  58. 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.
  59. What are the different ways a method can be overloaded?
    • Different parameter data types,
    • different number of parameters,
    • different order of parameters.
  60. 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.
  61. How do you debug an ASP.NET Web application?
    Attach the aspnet_wp.exe process to the DbgClr debugger.
  62. Difference between imperative and interrogative code.
    • Imperative functions are the one which return a value while
    • the interrogative functions do not return a value [void].
  63. Difference between value and reference type.
    • Value types - bool, byte, chat, decimal, double, enum, float, int, long, sbyte, short, strut, uint, ulong, ushort
    • Value types are stored in the Stack

    • Reference type - class, delegate, interface, object, string
    • Reference types are stored in the Heap