csharp-interview-2(senior, architect level)

Card Set Information

csharp-interview-2(senior, architect level)
2012-06-19 17:38:16
interview csharp programming net architect

csharp interview questions and answers - part 2 - senior, architect level
Show Answers:

  1. What is the difference between a.Equals(b) and a == b?
    • Equals checks type as well as it compares on heap
    • to objects whereas == doesn’t, it just check value on stack.  

    Both .Equals and == are used for comparison.

    • If both a and b are value type then you will get same result in a.Equals(b) and a == b.
    • But in case of reference type both behaves differently

    • string a = new string(new char[] { 'd', 'a', 'n', 'c', 'e' });
    • string b = new string(new char[] { 'd', 'a', 'n', 'c', 'e' });
    • object c = a;
    • object d = b; 

    • Console.WriteLine(a == b);        // True
    • Console.WriteLine(a.Equals(b));   // True
    • Console.WriteLine(c == d);  // False, since compares references to the objects, not values
    • Console.WriteLine(c.Equals(d));   // True
  2. How would one do a deep copy in .NET?
    • Implement ICloneable.
    • A deep copy is something that copies EVERY field of an
    • object. A shallow copy will only create a new object and point all the fields to the original.

    • using System.IO; // for MemoryStream
    • using System.Runtime.Serialization.Formatters.Binary; //
    • for BinaryFormatter

    //make sure the class/object you're doing a DeepCopy on is marked as Serializable

    • [Serializable]
    • public class DeepCopier
    • {
    •     public static T DeepCopy<T>(T obj)
    •     {
    •         object result = null;
    •         using (var ms = new MemoryStream())
    •         {
    •             var formatter = new BinaryFormatter();
    •             formatter.Serialize(ms, obj);
    •             ms.Position = 0;
    •             result = (T)formatter.Deserialize(ms);
    •             ms.Close();
    •         }
    •         return (T)result;
    •     }
    • }

    • string x = "asdfa";
    • string z = DeepCopier.DeepCopy(x);
  3. Explain current thinking around IClonable.
    • The System.ICloneable
    • interface defines a method of cloning—copying—to create a new instance of a class with the identical value as an existing instance.

    There are two ways to clone an instance:

    • 1.      Shallow copy - may be linked to data shared by both the original and the copy  
    • 2.      Deep copy - contains the complete encapsulated data of the original object 
  4. Explain the use of virtual, sealed, override, and abstract.
    • virtual keyword is used to modify a method or property declaration. It allows the downcasting from base class to derived class. From derived class’s point, the method overrides it specialised the implementation. To enforce the overriding, base method modify with abstract.
    • abstract keyword is used to modify a class, method or property declaration. You cannot instantiate an abstract class or make calls to an abstract method directly.
    • An abstract virtual method meaning that the method provides maybe a partial implementation, may be no implementation at all. And a derived class of it must implement it.
    • A sealed class cannot be derived. This modifier is most likely used on a static class. An abstract class cannot be sealed. A sealed override method in a derived class prevents it being further overridden.

    Virtual & Override keywords provides runtime polymorphism. A base class can make some of its methods as virtual which allows the derived class a chance to override the base class implementation by using override keyword.

    If method not virtual in base class, you can override it with new keyword in derived class
  5. Explain the differences between public, protected, private and internal.
    • Visibility differences on accessing a method, class:
    • private methods are only visible to a member in the same class;
    • protected methods are only visible to members in the derived class plus private scope;
    • internal methods/classes are visible to members in the same assembly;
    • public methods/class are visible to all.
  6. What is the difference between:
    catch(Exception e){throw e;}        and
    catch(Exception e){throw;}
    • catch(Exception e){throw e;}
    • suppress the original exception stack and begin a new exception flow. Original stack trace information maybe lost

    • catch(Exception e){throw;} 
    • re-throw original exception.
  7. What is the difference between typeof(foo) and 
    • Operatior typeof(foo) is used to obtain the System.Type object for a type at compile time.
    • myFoo.GetType() is used to obtain the exact run time type of an object. This method uses reflection.

    • Typeof is operator which applied to an object returns System.Type object.
    • Typeof cannot be overloaded while GetType has lot of overloads.
    • GetType is a method which also returns System.Type of an object. GetType is used to get the runtime type of the object.
  8. What is Serialization?
    • Serialization can be defined as “the process of storing the state of an object instance to some type of a storage medium".  In other words it is taking an object and then converting that object from its current form into some form for storage purposes, this can be a disk file or it might simply be in memory using MemoryStream for example, because you are simply copying the object. Or you may be sending an object between machines via .NET Remoting or a Web Service.
    • You would use serialization any place you need to take an "out of memory" snap shot of the object & persist it someplace else.
    • You have a few choices; you can either create your own "serialization” process that is using something like StreamReader, BinaryReader, or MemoryStream. For that matter you can use any object that can contain and persist the data.
    • Serialization is best implemented using the ISerializable interface.  XML Serialization using the default methods limits what you can serialize to public
    • declared members of a given object.  You can serialize any object with XMLSerialization but you can customize the Serialization process using the ISerializable interface.

    Here is an example of [binary] serialization:

    • FileStream fs = new FileStream("Test.dat", FileMode.Create);
    • BinaryFormatter formatter = new BinaryFormatter();
    • formatter.Serialize(fs, somestruct);
  9. What is Refactoring?
    Refactoring can be defined as "improving the design of existing code". It's a kind of global "code cleaning" exercise. There are many tasks you can perform on some code to improve it, and Refactoring is one of those tasks. Other tasks might be combining methods and applying new methodologies to existing code. Performing refactoring can range from the extremely simple to the extremely complex.
  10. What is Unit Testing?
    In computer programming, unit testing is a method by which individual units of source code, sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures, are tested to determine if they are fit for use.

    In Visual Studio  - Team Suite, independent - NUnit, plugin - ReSharper 
  11. What is a Delegate?
    A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method.

    • Delegates have the following properties:
    • * Delegates are similar to C++ function pointers, but are type safe.
    • * Delegates allow methods to be passed as parameters.
    • * Delegates can be used to define callback methods.
    • * Delegates can be chained together; for example, multiple methods can be called on a single event[multicast delegate]. Methods don't need to match the delegate signature exactly. For more information, see Covariance and Contravariance
    • * C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately defined method.

    • There are three steps in defining and using delegates:
    • * Declaration
    • * Instantiation
    • * Invocation
  12. Covariance and Contravariance in Delegates
    • Covariance permits a method to have a more derived return type than what is defined in the delegate.
    • Contravariance permits a method with parameter types that are less derived than in the delegate type.

    • class Mammals
    • {
    • }
    • // derived class
    • class Dogs : Mammals
    • {

    • class Program
    • {
    • // Define the delegate.
    • public delegate Mammals HandlerMethod();

    • public static Mammals FirstHandler() { return null; }
    • public static Dogs SecondHandler() { return null; }

    • static void Main()
    • {
    • HandlerMethod handler1 = FirstHandler; // Mammals

    • // Covariance allows this delegate. 
    • HandlerMethod handler2 = SecondHandler; // Dogs
    • }
    • }
    • --------------------------------------
    • Contravariance
    • // Event hander that accepts a parameter of the EventArgs type. (base for ...EventArgs)
    • private void MultiHandler(object sender, System.EventArgs e)
    • { label1.Text = System.DateTime.Now.ToString(); } 

    • public Form1()
    • {
    • InitializeComponent();

    • // You can use a method that has an EventArgs parameter,
    • // although the event expects the KeyEventArgs parameter.
    • this.button1.KeyDown += this.MultiHandler;

    • // You can use the same method
    • // for an event that expects the MouseEventArgs parameter.
    • this.button1.MouseClick += this.MultiHandler;
    • }
  13. Describe Delegates and Events connection.
    • The Event model in C# finds its roots in the event programming model that is popular in asynchronous programming. The basic foundation behind this programming model is the idea of "publisher and subscribers." In this model, you have publishers who will do some logic and publish an "event." Publishers will then send out their event only to subscribers who have subscribed to receive the specific event. In C#, any object can publish a set of events to which other applications can subscribe. When the publishing class raises an event, all the subscribed applications are notified.
    • Conventions
    •  The following important conventions are used with events:Event Handlers in the .NET Framework return void and take two parameters.
    • *The first paramter is the source of the event; that is the publishing object.
    • * The second parameter is an object derived from EventArgs.
    • * Events are properties of the class publishing the event.
    • * The keyword event controls how the event property is accessed by the subscribing classes.
  14. yield (C# Reference)
    • yield return <expression>;
    • yield break;

    The yield keyword signals to the compiler that the method in which it appears is an iterator block. The compiler generates a class to implement the behavior that is expressed in the iterator block. In the iterator block, the yield keyword is used together with the return keyword to provide a value to the enumerator object. This is the value that is returned, for example, in each loop of a foreach statement. The yield keyword is also used with break to signal the end of iteration.

    • public static System.Collections.IEnumerable Power(int number, int exponent)
    • {
    •     int counter = 0;
    •     int result = 1;
    •     while (counter++ < exponent)
    •     {
    •         result = result * number;
    •         yield return result;
    •     }
    • }

    • In a yield break statement, control is unconditionally returned to the caller of the iterator, which is either the IEnumerator.MoveNext method (or its genericSystem.Collections.Generic.IEnumerable<T> counterpart) or the Dispose method of the enumerator object.
    • The yield statement can only appear inside an iterator block, which can be implemented as the body of a method, operator, or accessor. The body of such methods, operators, or accessors is controlled by the following restrictions:Unsafe blocks are not allowed.Parameters to the method, operator, or accessor cannot be ref or out.

    A yield return statement cannot be located anywhere inside a try-catch block. It can be located in a try block if the try block is followed by a finally block.A yield break statement may be located in a try block or a catch block but not a finally block.A yield statement cannot appear in an anonymous method.
  15. Write prime c# code with yield
    • public static IEnumerable<int> Primes( int max )
    • {
    • yield return 2;
    • List<int> found = new List<int>();
    • found.Add( 3 );
    • int candidate = 3;
    • while ( candidate <= max )
    • {
    • bool isPrime = true;
    • foreach ( int prime in found )
    • {
    • if ( prime * prime > candidate )
    •  break;

    • if ( candidate % prime == 0 )
    • {
    • isPrime = false;
    • break;
    • }
    • }
    • if ( isPrime )
    • {
    • found.Add( candidate );
    • yield return candidate;
    • }
    • candidate += 2;
    • }
    • }
  16. yield (c#) logic
    The best way to think of it is that for the first call to the method, execution starts at the first line and continues until it hits a yield statement at which time it returns the value. The subsequent runs through the method continue execution at the statement after the yield, continuing to yield values or exiting at the end of the method.

    • // return integers from min to max-1
    • public static IEnumerable<int> Range( int min, int max )
    • {
    •   for ( int i = min; i < max; i++ )
    •      yield return i;

    Why not just iterate through the numbers yourself? The answer lies in the fact that each call maintains state, so you don’t have to.
  17. What are Generics?
    In C# development Generics provide a facility for generating data structures that are designed to handle specific types when declaring variables. Programmers define these parameterized types so that each variable of a particular generic type has the same internal algorithm.

    However, the types of data and method signatures can vary based on a programmer’s preference. To minimize the learning of Generics for developers, the creators of C# chose a syntax that matched the similar templates concept of C++. In C#, therefore, the syntax for generic classes and structures will utilize the same notations to identify the data types on which the generic declaration specializes.
  18. What is OOP?
    OOP - Object-oriented programming is a programming paradigm that uses "objects" - data structures consisting of datafields and methods together with their interactions - to design applications and computer programs. Programming techniques may include features such as data abstraction, encapsulation, modularity, polymorphism, and inheritance.
  19. Explain OOP
    • Class
    • A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind.
    • Object
    • An instance of a class. A class must be instantiated into an object before it can be used in the software. More than one instance of the same class can be in existence at any one  time.
    • Encapsulation
    • The act of placing data and the operations that performs
    • on that data in the same class. The class then becomes the 'capsule' or container for the data and operations.
    • Inheritance
    • The reuse of base classes (super classes) to form derived
    • classes (subclasses). Methods and properties defined in the superclass are automatically shared by any subclass.
    • Polymorphism
    •  Same interface, different implementation. The ability to substitute one class for another. This means that different classes may contain the same method names, but the result which is returned by each method will be different as the code behind each method (the implementation) is different in each class.

    A class defines (encapsulates) both the properties (data) of an entity and the methods (functions) which may act upon those properties. Neither properties nor methods which can be applied to that entity should exist outside of that class definition.