Author Topic: CSharp C# .NET 3.5 Interview Questions and Answers  (Read 16403 times)

Having spent a lot of the last 3 weeks interviewing for .NET C# roles with SQL I thought I might share the collection of questions and answers I have built up. Knowing AND UNDERSTANDING the answers to all of the following questions will give you a fantastic chance in most C# interviews.

Other general tips:

Read chapters 1 to 4 of for a full understanding of threading.

Read for a good and concise coverage of SQL 2008 basics.

Know your own CV! Know all the systems and business areas you have worked in, know the architecture and database designs. You will be asked questions on them, maybe asked to draw diagrams of them.

** C# .NET **
*    How can you copy a class?
   - A shallow copy copies all value types and reference values - references will still point to the same place in memory  myClass.MemberwiseClone();
   - A deep copy copies all fields and referenced objects to new memory, need to create a new

*    What is boxing?
   - Casting a value type as an object (ref type) type to allow it to be garbarge collected. Has an overhead and should be avoided.
      int a; object b = (obj)a;

*    Explain the garbage collecting with reference to generations
   - Generations exist to increase GC performance, Gen 0 objects are new, have never been observed by the GC, once the GC has run it compacts objects that are not collected and makes them Gen 1, on the next collection gen 1 is moved to gen 2 if its not collected. Gen 0 is collected more often since newer objects have shorter lives.

*    What would you use to store 1mil integer values?
   - array for small size, O(n) access
   - ArrayList is dynamic and has better access
   - best is List<t> (generic list) to save boxing/unboxing

*    How do you access a control from a worker thread?
   - Use a control.Invoke method (and usually an InvokeRequired to check if its required)

*    What is the difference between control.begininvoke/invoke?
   - .beginInvoke will run asynchronously
   - .Invoke will wait for the thread to complete before the calling thread continues

*    How do you think this is implemented 'under the hood'?
   - Control.InvokeRequired() to work out which is best

*    What is a delegate?
   - A type safe function pointer, a way of passing the code to run upon an event occurance. It encapulates a method as an object so it can be


*    What are the two different types of delegate?
   - Multicast or single. Multicast calls a number of methods in turn.

*    How is this different to calling begininvoke on a delegate?
   - BeginInvoke calls the delegate on a thread in the thread pool and returns to the calling thread imediately

*    How else could you do this?
   - Create your own thread explicitly and call the delegate

*    What are the methods on the Object class
   - Equals, ToString, GetHashCode, GetType, protected MemberWiseClone (makes a shallow copy - copies value type fields and references)

*    Why would you override any of the above methods?
   - Extend functionality / Provide custom functionality

*    Explain the Singleton pattern briefly
   - Can only ever be one instance, has Private constructor, public GetInstance method creates instance if there isnt on and returns instance reference.

*    If I needed to call a Win32 function, how would I do it?
   - P/invoke (platform invoke) or MC++ IJW. Be aware that is it unmanaged so needs manual garbage collection and error handling.

*    I want to create a custom control. What are my options?
   - Subclass control or an existing control and override the OnPaint method
     which passes you the rect and graphics surface to draw to,
     graphics.drawline etc

*    How do I draw outside of an OnPaint method
   - call control.CreateGraphics

*    What does the 'using' keyword do for you?
   - As a directive is means full namespaces dont have to be specified
      eg. using System
   - as a statement it automatically calls dispose when the object goes out of scope
     (assuming object is implements IDisposible)
      using (System.IO.StreamReader reader = new StreamReader("readme.txt"))
           // read from the file

      // readme.txt has now been closed automatically.

*    Explain what goes on in the garbage collector
   - GC stops all threads, marks and sweeps a generation from roots, compacts heap, puts
   finalizable objects on the finalise queue to be run, extra points for
   saying heap compaction results in fast allocs, and that position in the
   heap implies age/generation, and that un-needed finalisers result in more
   load on the GCollector process

*    How would you ensure something is cleared by the Garbage collector?
   - Implement IDisposable

*    How would I implement IDisposable?
     Why would I implement it?
        - Create a dispose(bool) and call dispose(true) from
   dispose method and dispose(false) from finaliser, set disposed flag,
   throw ObjectDisposedException if flag set on any subsequent call, call
   SupressFinalize in dispose call.
   Implemented to free up expensive resources

*    Can you call finalize on an object directly?
   - No, you can call GC.Collect or object.Dispose which may call the finalizer

*    How do I pass a value type as a reference?
   - use the 'ref' keyword eg void myfunc(ref int param)

*    Are structs ref or val type, how are they passed?
   - Value type (classes are referance types) to pass memory is copied onto the stack,

*    How about strings?   
   - Strings are immutable ref types

*    Whats the diff between
      MyClass A = (MyClass)obj;    and
      MyClass A = obj as MyClass;
   - static cast throws InvalidCastException and 'as' returns null if the cast is invalid

*    Whats new in .NET 3.5?
   - WCF/WPF/Linq/Lamda expressions/Var type/Object Initialisers/Extension Methods/Automatic Properties

*    How would you go about beginning a project? What tools would you use? Do you just start coding?
   - NUnit testing, UML, case diagrams, peer review, iterative test solutions etc, general chat

*    What is abstract vs interface?
   - Abstract class is a class but cannot be instantiated, it forces subclasses to have certain elements
     It may have some or no implementation and contains at least one abstract item which must be implemented by the subclass.
     You can only inherit from one abstract class
   - Interface is not a class, it has no implementation, you can implement multiple interfaces. All members are virtual and MUST be overridden by the implementing class.

*    What is overload vs override?
   - Overloading is the same method name with different parameters. Different Signature, maybe similar implementation.
   - Overriding is where a subclass implements the same method signature that is specified in its parent. Same signature, different implementation.

*    How can you hide the base implementation of a method?
*    What is the new keyword in overridden methods?
   - The new keyword in an overridden method if the base class isnt virtual. This will hide the base implementation.

*    What is an extension method?
   - Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

*    How can you write an extension method?
*    What is the this keyword?
   - Using the this keyword before the first parameter or a method indicates a static method is an extension method.
      eg   public static int WordCount(this String str) ...

*    Have you ever worked in a team that spanned more than one location?
     What issues came up and how did you solve them?
    - Basically can he handle ignorant oafs in a different time zone,
      is he diplomatic, and gives him a chance to chat a bit so I can get an idea on personality

*    Abstract class vs Interface
   - Abstract class cannot be instantiated and has one of more abstract methods but may have some implemented methods
     this seperates the base functionality from the variable. Abstract classes define core functions of a class.
   - Interface has no implemented methods and defines a template for how a class using the interface should be constructed

*    Set vs Collection
   - A set is a collection that contains no duplicate entries. This isnt included in System.Collections, can use HashSet<T> in .NET 3.5

*    Hashtable vs Dictionary?
   - Hashtable stores values in buckets with buckets having a hashcode based on the object key. Object in a Hashtable must implement GetHashCode.
   - Dictionary are the same as hashtable but are faster for value types because there is no boxing.

*    Try/Catch and Finally
   - Try catch allows you to attempt to use a resource and catch any exceptions. Finally is normally used to release the resource after the try block

*    What does the keyword Volitile signify in C#?
   - A property marked volitile may be changed by an outside entity. Often used for system values that are changing.

*    What is the difference between a value type and a reference type?
   - Value types are stored on the stack, reference types are stored on the heap with a reference from the stack.

*    What is int, value or reference?
   - Value, stored on the stack, passed by value

*    What is string, value or reference?
   - Reference, stored on the heap. Also immutable (cannot be changed)

*    Why should you not write a loop that has a core that adds bits to a string like this stringVar1+="stuff";
   - Strings are immutable so adding or modifing a string value actually creates a whole new string in memory then copying it over. This is relatively very slow. 

*    What class should you use for that sort of thing?
   - Should use StringBuilder, strings are only immutable to public interface, string builder only copies the added part of the string so is much faster. 

*    ADO.NET
   - A collection of OO Libraries to allow you to interact with data sources.

*    Can you make a derived method static if the parent is not static?
   - No

*    What is the difference between a DataSet and a DataReader?
   - Dataset is a colelction of DataTables. DataReader provides a stream of data from the database.

*    What does the access moddifier PROTECTED INTERNAL meant?
   - It means the object is protected (available from derived classed) OR internal (available from the same assembly)

*    What is managed code vs unmanged code?
   - Managed code runs in a runtime (CLR) The runtime handles garbage collection and exception handling.
     Unmanaged code talks to hardware, nothing is handled automatically. Good place to look for memory leaks.

*    Event vs Delegate
   - Interface cannot have a delegate but can have an event declaration
   - Events can only be raised by the class that declares an event, unlike delegate.

*    Exceptions in a multicast delegate or event?
   - If an exception is thrown in a multicast delegate or event the rest of the methods after the erroring one will not execute
     To overcome this use foreach(EventHandler handler in _myEvent.GetInvocationList()) and try catch each one individually
     Thread safety: you can lock on the (this) (current instance) when you take a copy of the delegate then iterate over the copy

*    What is CAS in .NET?
   - Code Access Security - the CAS policy is used by the CLR to maintain security.

*    What is are Func and Action? What is the difference?
   - Func and Action are predefined delegates with generic pararmeters. Func has an out parameter, Action does not
     Funcs used frequently with lambda     Func<int, int> sqr = x => x * x;
** Write code to ... **

*    Write a method to verify is a string is a palindrome and return a bool. Your method should ignore any punctuation.

*    Write a method to return the factorial of an int

Last Edit: June 17, 2011, 12:27:04 PM by sexytw #187;
Formerly sexytw

Re: CSharp C# .NET 3.5 Interview Questions and Answers
Reply #1 on: June 17, 2011, 11:56:28 AM
** Patterns **
*    Factory Pattern
   - For creating objects without specifing the exact class to be created.
     Seperates object creation code, useful for testing (cant use test constructors to create
     version of objects suitable for testing) or frameworks where code needs to create objects with types that may be subclassed.

*    Singleton Pattern
   - Restricts instantiation so only one object ever exists, usually uses a private constructor.
     Different from static in that you have more control over when the object is created.

*    What is your favorite pattern and give examples of where you have used it?

** XML**

*    Is XML case sentitive?
   - Yes

*    Can you have multiple elements with the same name?
   - Yes

*    Can an element have multiple attributes with the same name?
   - No

*    What are two models/APIs for reading an XML document?
   - DOM: Document Object Model - Creates an object model of tree nodes which you traverse to get to information
   - SAX: Simple API for XML - Fires events which must be manually handled and mapped to a custom object model. SAX is faster.

** Threading **

*    What is lock(x){ }
   - lock obtains a lock on the specified object so that only one thread can use it. It is a monitor with an addition try catch finally block to ensure if an exception is thrown the lock is always released.

*    What is monitor?
   - Lock without the exception handling, it protects an object from being used by more than one thread at a time. Monitor.Enter Monitor.Exit
     Monitor.Pulse and .Wait are used to send events to other threads, .Wait waits for a .Pulse event from another thread before continuing.

*    What is Mutex?
   - Mutex is a class in System.Threading. It can be used to serialize access to code, obtaining a lock on it until you call myMutex.close();
     It is different from monitor in that it can obtain a lock outsite of the scope of the process,so locking system resources from other process.

*    Monitor vs Mutex
   - Monitor is faster and uses less memory, Mutex can be used accross processes (is more flexible).

*    What is semaphore?
   - Semaphone is much like a monitor but it can allow a specified maximum number of threads to access an object. public Semaphore(int initialCount, int maximumCount);
*    What is AutoResetEvent?
   - AutoResetEvent is a construct that controls thread access to an object. When in Reset status no threads can access the object, once it is manually changed to Set status it allows one thread to access the object, once the thread passes through the AutoResetEvent AUTOMATICALLY changes back to Reset and stops more threads passing through.

*    What is ManualResetEvent?
   - Like AutoResetEvent but the lock is not automatically reset, it will continue to process one thread at a time (in Set state) until it is manually Reset

*    What is an interlocked class?
   - Interlocked performs tasks atomically ensuring they complete without being interupted by another thread. Operations are
     Increment/Decrement, exchange and compare-and-exchange. Compare checks a value and sets it as an atomic operation, eg an inUse flag.

** SQL **

    JOIN    Return rows when there is at least one match in both tables
    INNER JOIN   Same as JOIN - Return rows when there is at least one match in both tables.
    OUTER JOIN   Returns all rows from both tables even if there are no matched in the other table
    LEFT JOIN    Return all rows from the left table, even if there are no matches in the right table
    RIGHT JOIN   Return all rows from the right table, even if there are no matches in the left table
    FULL JOIN   Return rows when there is a match in one of the tables
    CROSS JOIN    Returns a Cartesian product of the two tables, all combinations. Same as SELECT * FROM [table 1], [table 2]
    UNION    Combines two or more SELECT statements. Only return distinct values
    UNION ALL   Combines two or more SELECT statements. Returns ALL values, distinct or now
    INTERSECT    Combines two or more SELECT statements. Returns values that exist in all result sets.
    ALIAS   Select Name From table_name AS alias_name

*    What is a transaction?
   - A way of making multiple statements atomic. Uses BEGIN TRANSACTION and COMMIT or ROLLBACK

*    Talk about indexs in SQL
       - Without an index SQL does a table scan (scane the whole table) to find information. Index allows queries to go directly
   to the relevant data which is much faster. Columns in an index must not be NULL

*    Talk about clustering in SQL
       - Physically orders the data

*    Truncate vs Delete?
   - Truncate is faster, it drops data but not table structure. It is not logged and does not fire triggers. It cannot be rolled back in a transaction. TRUNCATE TABLE customer.
   - Delete can have a WHERE clause, it is slower because it is logged and can be rolled back.

- Updates information about the keys in a table and updates query plans. This improves performance but takes a long time to run so shouldnt be done often.

*    Bit Limit on a row?
   - Around 8000 bytes (doesnt inlude Image or Text fields which are stored seperately) but a few big VARCHAR rows can hit this limit easily.

*    How many characters can VARCHAR hold? What if you need more?
   - 8000 characters but be aware or total row limit above.
     In SQL 2005 onwards there is VARCHAR(MAX) which can hold 2Gb, data is automatically stored in 'overflow pages' if it increases past the 8k limit.

*    How would you deal with a slow query
       - Remove cursors, add indexes (possibly clustered), update statistics, Query analyser to see where slow sections are

*    How can you make an SQL statement threadsafe?
   - Use TABLOCK, ROWLOCK or UPDLOCK to lock the table, row or say you are about to update the row again.

*    HAVING?
   - Used like WHERE in the case an aggregate function has been used (GROUP BY, SUM, AVG etc)

*    What does the floor function do?
   - rounds a number down to the nearest int
Formerly sexytw

0 Members and 1 Guest are viewing this topic.