C# Source Code: Sample C# Interview Questions
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Sample C# Interview Questions
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Wednesday, September 22, 2004
Hits:
18056
Category:
General/Framework
Article:
I often get asked to do technical interviews and always find myself struggling to find some sample questions. Anyway below are some sample questions which will help establish the extent of a candidates knowledge. I recommend reading Q34, just for entertainment value... Note, I will frequently update this page - so please check back for new questions. Q1. Basic Inheritance: a) Describe if each of the following lines of code compiles and will execute without exceptions. class Test { static void Main(string[] args) { // Line 1 Class2 a = new Class3(); // Line 2 Class3 b = new Class2(); // Line 3 Class2 c = (Class2)(new Class3()); // Line 4 Class3 d = (Class3)(new Class2()); // Line 5 Class2 e = (new Class3()) as Class2; // Line 6 Class3 f = (new Class2()) as Class3; } } public class Class2 { } public class Class3: Class2 { } b) What results would you expect from running the code below? using System; class A { public void F() { Console.WriteLine("A.F"); } public virtual void G() { Console.WriteLine("A.G"); } } class B: A { new public void F() { Console.WriteLine("B.F"); } public override void G() { Console.WriteLine("B.G"); } } class Test { static void Main() { B b = new B(); A a = b; a.F(); b.F(); a.G(); b.G(); } } Q2. More Inheritance: What results would you expect from running the code below? using System; class A { public virtual void F() { Console.WriteLine("A.F"); } public void G() { Console.WriteLine("A.G"); } } class B: A { public override void F() { Console.WriteLine("B.F"); } new public virtual void G() { Console.WriteLine("B.G"); base.G(); } } class C: B { new public virtual void F() { Console.WriteLine("C.F"); } new public virtual void G() { Console.WriteLine("C.G"); base.G(); } } class D: C { public override void F() { Console.WriteLine("D.F"); } public override void G() { Console.WriteLine("D.G"); base.G(); } } class Test { static void Main() { D d = new D(); A a = d; B b = d; C c = d; a.F(); a.G(); Console.WriteLine("---END A---"); b.F(); b.G(); Console.WriteLine("---END B---"); c.F(); c.G(); Console.WriteLine("---END C---"); d.F(); d.G(); Console.WriteLine("---END D---"); D e = new D(); B f = e; f.G(); Console.WriteLine("---END E---"); Console.ReadLine(); } } Q3. What does the ThreadStatic attribute do? Q4. What does the "Volatile" modifier do? Q5. Does C# support multiple inheritance? Q6. When you inherit a protected class-level variable, who is it available to? Q7. Describe the accessibility modifier "protected internal". Q8. C# provides, by default a parameterless constructor. If I write a constructor that takes a string as a parameter, but want to keep the parameterless constructor. How many constructors should I write? Q9. Can you allow a class to be inherited, but prevent a method from being overridden? Q10. What's the difference between an interface and abstract class? Q11. If a base class has overloaded constructors, and an inherited class also has overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor? Q12. What's the advantage of using System.Text.StringBuilder over System.String? Q13. What is the following attributes do? a) [EditorBrowsable] b) [Browsable] c) [DesignerSerializationVisibility] d) [DesignTimeVisible] e) [DefaultValue] Q14. Can multiple catch blocks be executed? Q15. Try Catch Finally blocks a) If an exception is thrown inside a catch block, will the finally block be still be called? b) If none of the catch blocks contain a matching exception type, what will happen? c) There is an illegal return statement. Say which one it is and why. try { return; } catch { return; } finally { return; } d) What output would running the following code generate: try { throw new InvalidCastException ("A"); } catch( InvalidCastException ex ) { Console.WriteLine( ex.Message ); throw new ArgumentException("B"); } catch( ArgumentException ex ) { Console.WriteLine( ex.Message ); throw new ArithmeticException("C"); } finally { Console.WriteLine("FINALLY"); Console.ReadLine(); } Console.WriteLine("EXIT"); Console.ReadLine(); Q16. Explain ACID rule of thumb for transactions. Q17. Write code to resize a System.Drawing.Rectangle, decreasing it's width and height by one unit. Q18. Virtual/Static Methods: a) Can you declare an overriden method as static? b) Can a static method be declared as virtual? c) Can you override a private virtual method? d) Can an interface method be declared as virtual? Q19. Describe the different database locking mechanisms you have used and discuss their merits. Q20. How would you go about making an object cloneable (inc. interface/s and namespaces)? Q21. What's the difference between and background and foreground thread? Q22. Structs v Classes. What results would you expect from the following and why? using System; class HumanClass { public string Name; } struct HumanStruct { public string Name; } class RunTest { public static void ChangeName(HumanStruct human) { human.Name = "James"; } public static void ChangeName(HumanClass human) { human.Name = "James"; } public static void ChangeName(ref HumanStruct human) { human.Name = "James"; } public static void ChangeName(ref HumanClass human) { human.Name = "James"; } public static void Main() { HumanStruct a = new HumanStruct(); HumanClass b = new HumanClass(); a.Name = "Andrew"; b.Name = "Andrew"; ChangeName(a); ChangeName(b); Console.WriteLine("Val Calls"); Console.WriteLine("a.Name = {0}", a.Name); Console.WriteLine("b.Name = {0}", b.Name); Console.WriteLine("Ref Calls"); a.Name = "Andrew"; b.Name = "Andrew"; ChangeName(ref a); ChangeName(ref b); Console.WriteLine("a.Name = {0}", a.Name); Console.WriteLine("b.Name = {0}", b.Name); Console.ReadLine(); } } Q23. Structs a) Can a struct inherit from another struct? b) Can a struct inherit from another class? c) Can a struct be the base of another class? d) Can a struct implement an interface? Q24. Finalizers a) Describe the basic process of finalization. b) When should you use a finalizer? c) What access protection should you give your finalizer? d) Write a stub class which impliments both a finaliser and the IDisposable interface. Demonstrate how to prevent a disposed objects from being finalized. e) How and when would you go about preventing the finalizer being called for a specific object? Q 25. Arrays a) What is the difference between a rectangular and jagged array? b) Write the declaration for a 3d rectangular and 3d jagged array. c) Does the Clone method of an array perform a deep or shallow copy (explain the difference between the two)? Q 26. Value Types Write the code to define a new value type called "Andrew" which overloads the inequality and equality operators, and overrides the equality operator. The value type must have a single integer property called "Age" which should be used in the compairsons. The code below demonstrates a simple test for the new value type: Andrew a = new Andrew(), b = new Andrew(); a.Age = 10; b.Age = 10; // This should return true Console.WriteLine(b == a); a.Age = 11; // This should return false Console.WriteLine(b == a); Q 27. Explicit Interfaces a) Will the following class compile? b) Discuss the way the interface has been implimented and when would you use this? interface ISomeInterface { string Key{ get; } } public class myClass : ISomeInterface { ///
/// Gets the object key. ///
public string Key { get{ return "Andrew"; } } ///
/// Gets the object key. ///
public string ISomeInterface.Key { /// Delegate the inteface call to the Key property. get{ return this.Key; } } } Q 28. Dates Write a simple function that takes a date and return which quarter that date is in (ie dates from January through to March will return 1, dates from April through to June will return 2 etc). Q 29. Iterators Write some example source code iterating through a collection using GetEnumerator(). What is the difference between using GetEnumerator() and writing a foreach loop? Q 30. IDisposable Write the results you would expect to see from running the following code: class EntryPoint { static void Main(string[] args) { try { TestResource test = new TestResource("TEST 1"); throw new Exception("TEST MESSAGE"); test.Dispose(); } catch{} try { TestResource test = new TestResource("TEST 2"); test = null; } catch{} try { using( TestResource test = new TestResource("TEST 3") ) { throw new Exception("TEST MESSAGE"); } } catch{} System.GC.Collect(); Console.ReadLine(); } } class TestResource: IDisposable { private string _disposeMessage = string.Empty; ///
/// Default constructor. ///
///
Dispose message public TestResource(string disposeMessage) { _disposeMessage = disposeMessage; } ///
/// Disposes of resources. ///
public void Dispose() { Console.WriteLine( "{0}. Message {1}. Dispose Called", DateTime.Now, _disposeMessage ); } } Q 31. Value and Reference Type Conversions a) What output would you expect the following code to return and explain what's happening? struct Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } Point p = new Point(10, 10); object refPoint = p; p.x = 20; Console.Write(((Point)refPoint).x); b) What would you expect the following code to return and comment on the difference between the comparisons: string a = "hello"; string b = "h"; string c = "hello"; b += "ello"; // append to b string d = String.IsInterned(b); Console.WriteLine( "Test 1: " + (a == b) ); Console.WriteLine( "Test 2: " + Object.Equals( a, b) ); Console.WriteLine( "Test 3: " + ((object)a == (object)b) ); Console.WriteLine( "Test 4: " + Object.ReferenceEquals(a, c) ); Console.WriteLine( "Test 5: " + (c == a) ); Console.WriteLine( "Test 6: " + Object.ReferenceEquals(a, d) ); c) Given the following: public enum MyEnum { Foo, Bar } object a = MyEnum.Foo; object b = MyEnum.Foo; What are the values of the following expressions, and why? • a == b • a.Equals(b) • Object.Equals(a, b) • Object.ReferenceEquals(a, b) Q 32. Reference to a Value type Write example code that obtains a reference to a value type (eg a struct) and prove that the reference points to this value type. Q 33. Basic Maths a) Carefully add the following numbers in your head. Take 1000 and add 40 to it. Now add another 1000. Now add 30. Add another 1000. Now add 20. Now add another 1000 Now add 10. What is the total? b) Calculate 19 * 17 in your head? Q 34. Logic Think carefully before giving your answer. a) You are participating in a race. You overtake the second person. What position are you in? b) If you overtake the last person, then what position are you in? c) Knight Rider is driving 100mph towards the Truck. The truck lowers its ramp and Knight Rider drives onto the ramp at 100mph. Describe what happens to both sets of wheels as they hit the ramp. Does it make a difference if the car is front or rear wheel drive? d) Should you pour the lemonade before or after the beer when making a beer shandy and why? e) Describe the different ways in which you could ascertain the weight of the human head. f) If you are driving at 30 mph in an open top land rover in the bush and a fly is flying next to you, does this mean the fly is also flying at 30mph. Discuss... g) Could a ultra sharp but frictionless knife, cut into an ultra smooth frictionless surface? h) Can the average human outrun a bumble bee? i) Estimate the speed (if any) that would be required before a human can run on water. j) If you fell from 1 mile up into the sea, describe what strategy you would adopt to survive the water landed and why (ie head first, feet first, bottom first etc)? k) What time would you estimate the average human would do the 100m if they had to run backwards? l) If you covered you hand in parafin and ignited it do you think it is possible to put it out by waving it around? Explain. m) What do wasps eat? Q 35. Case Statements What will happen in each of the following case statement blocks? a) int x = 1; switch(x) { case 0: case 1: default: { Console.WriteLine("X = " + x.ToString() ); break; } } b) int x = 1; switch(x) { case 0: { Console.WriteLine("X = " + x.ToString() ); } case 1: { Console.WriteLine("X = " + x.ToString() ); } default: { Console.WriteLine("X = " + x.ToString() ); break; } } c) int x = 1; switch(x) { case 0: goto case default; case 1: goto case default; default: { Console.WriteLine("X = " + x.ToString() ); break; } } Q 36. Basic Delegates Define a delegate to call the "MyFunction" method of the "CallOnMe" class. Your code should also include an example of how to invoke and return the results from this delegate. The class is defined below: public class CallOnMe { public string MyFunction(string myValue) { return "Answer: " + myValue ; } } Q 37. Basic Database and ADO Questions a) What is the role of the DataReader class in ADO.NET connections? b) What is a pre-requisite for connection pooling? Q 38. ASP.NET Basics a) Explain the differences between Server-side and Client-side code? b) What are some ways to manage state in an ASP.Net application? c) What does the "EnableViewState" property do? Why would I want it on or off? d) What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other? e) How can I maintain Session state in a Web Farm or Web Garden? f) What base class do all Web Forms inherit from? g) What does WSDL stand for? What does it do? h) Which WebForm Validator control would you use if you needed to make sure the values in two different WebForm controls matched? i) What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeater control? Q 39. Architecture a) Describe the three tier or n-Tier model. b) Name some of the Microsoft Application Blocks. Have you used any? Which ones? Q 40. Basic Locking a) Describe the two different locking strategies employed in the code below. b) Which (if any) of these strategies guarantee method level synchronisation to a collection? c) How do you create a synchronised hashtable? What considerations need to be made when using enumerators on synchronised collections? d) What is the point of the SyncRoot object? // Define two hashtables private static Hashtable _ht1; private static Hashtable _ht2; static void Main(string[] args) { // Create collection _ht1 = new Hashtable(); _ht2 = new Hashtable(); // Create threads Thread th1 = new Thread( new ThreadStart( _TestLock1 ) ); Thread th2 = new Thread( new ThreadStart( _TestLock2) ); // Start threads th1.Start(); th2.Start(); // Wait for threads to startup Thread.Sleep(50); // Add to hash tables _ht1.Add( "-1",-1); _ht2.Add( "-1",-1); } ///
/// Adds to Hashtable 2 ///
private static void _TestLock1() { // Lock the SyncRoot object lock( _ht1.SyncRoot ) { // Add to has table for ( int i = 0 ; i < 200; i++ ) { _ht1.Add ( i.ToString(), i ); Thread.Sleep( 1000 ); } } } ///
/// Adds to Hashtable 2 ///
private static void _TestLock2() { // Lock the hashtable object lock( _ht2 ) { // Add to has table for ( int i = 0 ; i < 200; i++ ) { _ht2.Add ( i.ToString(), i ); Thread.Sleep( 1000 ); } } } Q 41. Interfaces Will the code below compile? If so, write code to return the string "Driving my car home". public abstract class Car { public virtual void Start() {} public virtual void Park() {} } public interface ICompanyCar { string Drive(); } public interface IPersonalCar { string Drive(); } public class MyCar : Car, ICompanyCar, IPersonalCar { string ICompanyCar.Drive() { return "Driving my car to work"; } string IPersonalCar.Drive() { return "Driving my car home"; } } Q 42. Interface Members Which of the following can be an interface member? a. Constructors or destructors b. Static members c. Constants d. DataFields e. Events f. Finalizers Q 43. Static Constructors When is a static constructor called? a. When the application is first loaded into memory. b. After the first instance of the class is created. c. Before the first instance of the class is created, or before the first static method is called. d. Static constructors are indeterminate, ie. they are called at unpredictable times. Q 44. Operators Describe what results you would expect to see returned from the following and explain why: public enum myEnum { x, y } class TestClass { static void Main(string[] args) { Console.WriteLine( "1 " + Equals1( myEnum.x, myEnum.x ) ); Console.WriteLine( "2 " + Equals2( myEnum.x, myEnum.x ) ) ; Console.WriteLine( "3 " + Equals3( myEnum.x, myEnum.x ) ); Console.WriteLine( "4 " + Equals4( myEnum.x, myEnum.x ) ); Console.WriteLine( "5 " + Equals5( myEnum.x, myEnum.x ) ); } public static bool Equals1(object x, object y) { return x == y; } public static bool Equals2(myEnum x, myEnum y) { return x == y ; } public static bool Equals3(object x, object y) { return Object.Equals( x , y ); } public static bool Equals4(object x, object y) { return x.Equals( y ) ; } public static bool Equals5(object x, object y) { return ((myEnum)x).Equals( y ) ; } } Q 45. Operators Write a small code snippet that demonstrates how you would go about overloading the && and || operators. Q 46. Remoting a) What are the consideration in deciding to use .NET Remoting or ASP.NET Web Services? b) What are remotable objects in .NET Remoting? c) What’s SingleCall activation mode used for? d) What’s Singleton activation mode? e) How do you define the lease of the object? f) What are channels in .NET Remoting Q 47. Architecture What is Cyclomatic complexity? Q 48. Security Attributes What benefit does your code receive if you decorate it with attributes demanding specific Security permissions? Q 49. Native Image Cache What is native image cache and where is it stored? Q 50. Shallow Copy, Deep Copy and MemberWiseClone What is the difference between shallow and deep copying? How does MemberWiseClone method work? Q 51. General What does the following code snippet return? double expectedValue = 1/2; if ( expectedValue > 0 ) { expectedValue = expectedValue + 0.5; } Console.WriteLine(expectedValue); Q 52. Control/Component constructors What is the purpose of the following type of constructor and what type of control/component should use it? public MyControl(IContainer container) : this() { container.Add(this); } Q 53. Readonly keyword When can variables declared with the readonly keyword be assigned? Q54. Events, Timers and GC a) What output will the following code produce? b) What will the results be if you uncomment the line "//GC.Collect;"? class TestClass { ///
/// The main entry point for the application. ///
[STAThread] static void Main(string[] args) { TestEventCaller te = new TestEventCaller(); te.Start(); te = null; //GC.Collect; Console.WriteLine("Waiting..."); Console.ReadLine(); } } class TestEventCaller { public void Start() { TestEventSender te = new TestEventSender(); te.GeneralEvent +=new EventHandler(te_GeneralEvent); te.Start(); te = null; } private void te_GeneralEvent(object sender, EventArgs e) { Console.WriteLine("Received GeneralEvent"); } } class TestEventSender { public event EventHandler GeneralEvent; public void Start() { System.Threading.Timer tm = new System.Threading.Timer( new TimerCallback(_OnGeneralEvent), null, 1000, Timeout.Infinite ); tm = null; } private void _OnGeneralEvent( object notUsed ) { if ( GeneralEvent != null ) { Console.WriteLine("Calling GeneralEvent"); GeneralEvent(this, EventArgs.Empty ); } else { Console.WriteLine("GeneralEvent is Null"); } } } Q 55. Threading a) What is an atomic operation and what does the Interlock class do? b) Describe what the following code does (I wrote this in notepad - so hope it compiles!). namespace ParallelTasks { using System; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Net; class ParallelInvoke { static void Main() { string[] words = CreateWordArray(@"http://www.gutenberg.org/files/2009/2009.txt"); Parallel.Invoke(() => { Console.WriteLine("Begin first task..."); AA1(words); }, // close first Action () => { Console.WriteLine("Begin second task..."); AA2(words); }, //close second Action () => { Console.WriteLine("Begin third task..."); AA3(words, "species"); } //close third Action ); Console.WriteLine("Returned from Parallel.Invoke"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } #region HelperMethods private static void AA3(string[] words, string term) { var findWord = from word in words where word.ToUpper().Contains(term.ToUpper()) select word; Console.WriteLine("Task 1: " + findWord.Count()); } private static void AA2(string[] words) { var frequencyOrder = from word in words where word.Length > 6 group word by word into g orderby g.Count() descending select g.Key; var x = frequencyOrder.Take(10); StringBuilder sb = new StringBuilder(); sb.AppendLine("Task 2:"); foreach (var v in x) { sb.AppendLine(" " + v); } Console.WriteLine(sb.ToString()); } private static string AA1(string[] words) { var x= (from w in words orderby w.Length descending select w).First(); return x; } static string[] CreateWordArray(string uri) { Console.WriteLine("Retrieving from {0}", uri); string s = new WebClient().DownloadString(uri); return s.Split( new char[] { ' ', '\u000A', ',', '.', ';', ':', '-', '_', '/' }, StringSplitOptions.RemoveEmptyEntries); } #endregion } } Q 56. Interop Convert the following VB code to C# Private Declare Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" (ByVal idHook As Long, ByVal lpfn As Long, ByVal hmod As Long, ByVal dwThreadId As Long) As Long Sub ExampleCall() Dim hHook As Long hHook = SetWindowsHookEx(WH_CBT, AddressOf MsgBoxHookProc, 0, 0) End Sub Public Function MsgBoxHookProc(ByVal uMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long MsgBoxHookProc = False End Function Q 57. SQL Server a) What will the table AJB_TEST contain after running the following SQL? begin tran CREATE TABLE AJB_TEST ( [TEST] [char] (10) NOT NULL ) declare @var int insert into AJB_TEST values('AJB1') select TOP 1 convert(int,TEST) from AJB_TEST insert into AJB_TEST values('AJB2') commit tran b) What will the table AJB_TEST contain after running the following SQL? begin tran CREATE TABLE AJB_TEST ( [TEST] [char] (10) NOT NULL ) insert into AJB_TEST values(null) insert into AJB_TEST values('AJB1') commit tran c) What methods or settings could you use to alter the results in the previous two sql scripts? Q 58. General What does the following code output to the console window? class TestApp { static void Main() { int f = 0; f = ReturnAddOrSub(ref f) * 3; Console.WriteLine(f); } static int ReturnAddOrSub(ref int f) { int retValue = (f == 0) ? f++ : f--; return retValue; } } Q 59. Threading and Memory Barriers What does the following code produce and why? private static void Main() { // A foreach (string word in "Fire walk with me!".Split(new[] { ' ' })) { ThreadPool.QueueUserWorkItem(_ => Console.WriteLine(word)); } Console.ReadKey(); // B foreach (string word in "Fire walk with me!".Split(new[] { ' ' })) { var theWord = word; ThreadPool.QueueUserWorkItem(_ => Console.WriteLine(theWord)); } Console.ReadKey(); // C foreach (string word in "Fire walk with me!".Split(new[] { ' ' })) { ThreadPool.QueueUserWorkItem(_ => Console.WriteLine(word)); Thread.Sleep(16); } Console.ReadKey(); } Q60 Database Indexes a) Which of the following comments are true for a SQL server clustered index? 1) You may have a maximum of one clustered index per table. 2) You may have a maximum of two clustered indexes per table (one descending and one ascending). 3) Clustered indexes determine how the table is written to disk. 4) Clustered indexes are the most performant type of index. b) Which of the following comments are true for a SQL server non-clustered index? 1) You may have a maximum of one non-clustered index per table. 2) You may have a large number of non-clustered indexes per table. 3) Non-clustered indexes determine how the table is written to disk. 4) Non-clustered indexes are the most performant type of index. c) Which of the following comments are true for a SQL server covered index? 1) You may have a maximum of one covered index per table. 2) A covered index is an index which contains all the fields required by a specific fetch statement. 3) Covered indexes are the most performant type of non-clustered index (if design for a specific query). ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- Answers: A 1. Basic Inheritance. a) Line 1: Compiles + Runs. Line 2: Doesn't Compile. Line 3: Compiles + Runs. Line 4: Compiles + Throws invalid cast exception. Line 5: Compiles + Runs. Line 6: Compiles + Runs. b) A.F // Not B.F, since since class b uses the "new" keyword which breaks the inheritance tree. B.F B.G B.G A 2. More Inheritance. B.F A.G ---END A--- B.F B.G A.G ---END B--- D.F D.G C.G B.G A.G ---END C--- D.F D.G C.G B.G A.G ---END D--- B.G A.G ---END E--- A 3. A static variable marked with ThreadStaticAttribute is not shared between threads. Each executing thread has a separate instance of the field, and independently sets and gets values for that variable. If the variable is accessed on a different thread, it will contain a different value. Note, do not specify initial values for variables marked with ThreadStaticAttribute, because such initialization occurs only once when the class constructor executes (and therefore only applys to the thread that created the class). Your code should expect the field to be initialized to it's default value for value types, or to a null reference if it is a reference type. Variables marked with the ThreadStaticAttribute are by definition thread safe. A 4. The system always reads the current value of a volatile object at the point it is requested, even if the previous instruction asked for a value from the same object. Also, the value of the object is written immediately on assignment (the ordering of writes and reads is always preserved). The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access. Using the volatile modifier ensures that one thread retrieves the most up-to-date value written by another thread. I will update this will more q's shortly.... A 5. No, you can only inherit from a single object. But you can expose multiple interfaces. A 6. A derived protected variable is only accessible in the derived class. A 7. The variable or field will be available to derived classes and classes within the same Assembly (+ the base class it?s declared in). A 8. Two. Once you write another constructor, C# will remove the implicit parameterless constructor (unless you are writting a struct which always contain a parameterless constructor). A 9. Yes, just leave the class public and make the method sealed. A 10. 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. A 11. Yes, just place a colon and the keyword "base" followed by the parameter list to invoke the appropriate constructor. You can use the same symantics to invoke other constructors in the current class, using the "this" keyword in place of "base". See below for an example: eg. // Base class Public class Person { public Person(string name) { Debug.WriteLine("(Base Class) Person: " + name); } } // User class. Derives from person public class User: Person { public User(string name, int age) :base(name) // Call the name constructor of the base class { Debug.WriteLine("Person: " + name + " age = " + age.ToString()); } public User(string name, int age, string loginName) :this(name, age) // Call the name, age constructor of this class { Debug.WriteLine("Person: " + name + " age = " + age.ToString() + ", login = " + loginName); } } A 12. StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string variable is altered a new instance will be created. A 13. a) EditorBrowsableAttribute. You can use this class in a visual designer or text editor to determine what is visible to the user. For example, the IntelliSense engine in Visual Studio .NET uses this attribute to determine whether to show a method or property. The values for this attribute are: [Advanced] The property or method is a feature that only advanced users should see. An editor can either show or hide such properties. [Always] The property or method is always browsable from within an editor. [Never] The property or method is never browsable from within an editor. b) BrowsableAttribute. A visual designer typically displays in the Properties window those members that either have no browsable attribute or are marked with the BrowsableAttribute constructor of the value true. These members can be modified at design time. Members marked with the BrowsableAttribute constructor of the value false are not appropriate for design-time editing and therefore are not displayed in a visual designer. The default is true. c) DesignerSerializationVisibilityAttribute. Specifies the type of persistence to use when serializing a property on a component at design time. d) DesignTimeVisibleAttribute. Marks a component's visibility. If DesignTimeVisibleAttribute.Yes is present, a visual designer can show this component on a designer e) DefaultValueAttribute. You can create a DefaultValueAttribute with any property value. A member's default value is typically its initial value. A visual designer can use the default value to reset the member's value. Code generators can use the default values also to determine whether code should be generated for the member. A 14. No, once a matching catch exception signature is found the control will be transferred to the finally block (if there are any). A 15. Try, Catch, Finally blocks a) If the catch clauses throws an exception the finally clause WILL be called before the exception is propagated up the call stack. b) None of the other catch blocks will be called and the exception will be treated as a unhandled exception (i.e. the exception will be propagated up the call stack). If there is a finally block this will get called before propogating this unhandled exception. Note, a generic exception handler takes the form: try { } catch(Exception ex) { } finally { } c) The return statement inside the finally block is illegal, since you cannot leave the body of a finally clause. The above question was submitted by Gilbert Rosal. d) The code will output: A Unhandled Exception: System.ArgumentException: B at TestClass.Main(String[] args) in c:\test\consoleapplication7\class1.cs:line 26 FINALLY Note, the last 2 lines of code compiles with an "unreachable code" warning: Console.WriteLine("EXIT"); Console.ReadLine(); A 16. ACID transactions: Atomic: 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 rolled back. It cannot be in an "in-between" state, where something has been updated and something has not. Isolated: No transaction should see the intermediate results of the current transaction. Durable: The values persist if the data had been committed even if the system crashes right after. A 17. Resize Rectangle: // Create a rectangle Rectangle rect = new Rectangle(0, 0, 10, 10); // Reduce it's width and height by one. rect.Inflate(-1, -1); A 18. Virtual/Static Methods: a) No. The signature of an overriden method must remain the same. b) No. Static methods cannot be virtual. c) No. Private methods are inaccessible in derived classes. Note, the compiler won't actually allow you to declare a private method as virtual. d) Yes. Interface methods can be declared as virtual. A 19. Candidate should explode into a lengthy rant and cover the following topics: a) Optimistic locking - assumes that collisions are unlikely and therefore only gets a lock just before you try to commit your changes. b) Pessimitic locking - assumes that your changes will collide with another user's and hence locks all the rows you are updating as you read them. c) Versioning - uses a version number column on each table to detect if any changes have been made. Often useful to have a "last updated" and "last updated by" column as well. d) Timestamps - same as above but using the timestamp data type gives you an automatically updating column. A 20. Implement "ICloneable" eg: using System.Runtime.Serialization.Formatters.Binary; ///
/// Clones this object using a binary formatter (virtual method). ///
///
Clone of object.
public virtual object Clone() { // Create a new memory stream using (Stream stream = new MemoryStream()) { // Use binary formatter to serialize this object BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(stream, this); // Reset the position back to the start of the stream stream.Position = 0; return binaryFormatter.Deserialize(stream); } } A 21. A foreground thread runs indefinitely, while a background thread terminates once the last foreground thread has stopped. You can use the IsBackground property to determine or change the background status of a thread. Note, this is not the same as thread priority which determines the allocation of processor time based on the priorities of the running threads. A 22. Structs vs Class: Val Calls a.Name = Andrew b.Name = James Ref Calls a.Name = James b.Name = James The output of the example shows that only the value of the class field was changed when passing the parameters by value. The struct field, did not change since a COPY of the struct is passed to the method (rather than a reference to the class). When the methods are called by ref, both values change since the struct no longer gets copied. A 23. a) No. b) No. c) No. d) Yes, eg: interface IImage { void Paint(); } struct Picture : IImage { public void Paint() { // painting code goes here } private int x, y, z; // other struct members } A 24. Finalizers a) When an object with a finalizer is collected, it's not immediately removed from memory. Instead, a reference to the object is placed in a special finalization queue. A dedicated finalization thread then calls the finalizer and then marks the object as no longer requiring finalization before removing it from the finalization queue. Until finalization is complete, the queue's reference to the object is sufficent to keep the object alive. After finalization the object will be reclaimed during the next garbage collection. When an object is finalized, other objects that it refers to may have already been finalized. During finalization, you can safely free external resources such as operating system handles or database connections, but objects on the managed heap SHOULD NOT BE REFERENCED. b) Avoid creating finalizers whenever possible. Objects with finalizers are more costly as they maintain their existance through at least two garbage collection passes. Finalizers should only be used for disposing on unmanaged handles or other such resources. c) Finalizers should always be declared as protected. Never expose a finalizer. d) The code should look something like the block below. Note, the GC.SuppressFinalize which prevents the finalizer being called if the client has correctly called the Dispose method. public class DemoFileHandleClass: IDisposable { IntPtr handleToSomeResource; ///
/// Object finaliser ///
~DemoFileHandleClass() { Dispose(false); } ///
/// Disposes of objects resources ///
public void Dispose() { Dispose(true); } ///
/// Protected dispose method, handles releasing resources. ///
///
protected void Dispose(bool disposing) { if ( disposing ) { // Object has been correctly disposed of, // prevent finalizer from being called GC.SuppressFinalize(this); // Dispose of mananged objects here } // Release unmanaged/external resources } } e) The GC.SuppressFinalize() method prevents a finalizer from being called. You would normally do this in the Dispose method of an object that implements the IDisposable interface. Once the Dispose method has been explicitly called and has released all relevant resources you generally no longer need the garbage collector to call Object.Finalize. A 25. Arrays a) Are rectangular array has consistent array dimensions whereas jagged arrays have varying length dimensions. b) 3d rectangular array: string[,,] userNames; 3d jagged array: string[][][] userNames; c) It performs a shallow copy, i.e. any reference types that are in the array are not copied. A 26. Value Type public struct Andrew { private int _age; ///
/// Overload the equality operator (tests the ages are the same). ///
///
True if objects are the same age.
public static bool operator ==(Andrew a, Andrew b) { return a.Age == b.Age; } ///
/// Overload the equality operator (tests the age is ///
///
True if objects are the same age.
public static bool operator !=(Andrew a, Andrew b) { return a.Age != b.Age; } ///
/// Overrides the Object.Equals method. ///
///
///
Returns true if the objects are the same /// or their ages are the same.
public override bool Equals(object obj) { bool result = false; if ( obj != null ) { if ( (object)this == obj ) { // References are the same result = true; } if ( obj is Andrew ) { // Test if the ages are the same return ((Andrew)obj).Age == this.Age; } } return result; } ///
/// Gets or sets the age of an object. ///
public int Age { get{ return _age; } set{ _age = value; } } ///
/// Return the hash code ///
///
public override int GetHashCode() { return _age; } } A 27. Explicit Interfaces a) No the class will not compile as the interface has the "public" modifier infront of it. b) You use explicit interfaces when don't want the interface calls to accessible via the type that impliments it. A 28. Dates ///
/// Returns the quarter for the the week supplied (i.e. the Friday). ///
///
The date to return the quarter for. ///
An integer value between 1 and 4 representing the quarter for the supplied date.
public static int GetQuarter(DateTime date) { return System.Convert.ToInt32(Math.Ceiling(date.Month / 3d)); } The function should look something like the above code. Note that you need to append the number 3 with a "d" character to force the calculation to return a double. The candiate could also use a simple switch statement, but this is a less optimal answer. A 29. Iterators Example iterating through a collection using GetEnumerator. There is no difference between using GetEnumerator() and writing a foreach loop, they compile to the same instructions. // Create a string dictonary StringDictionary myDictonary = new StringDictionary(); myDictonary.Add("User1","Andrew Baker"); myDictonary.Add("User2","David Beckham"); // METHOD A: Console.WriteLine("METHOD A"); // Iterate through the dictonary using IEnumerator IEnumerator iEnum = myDictonary.GetEnumerator(); while(iEnum.MoveNext()) { // Cast the current value to a dictionary entry DictionaryEntry de = (DictionaryEntry)iEnum.Current; Console.WriteLine("Key: {0}, Value: {1}.", de.Key, de.Value); } // METHOD B: Console.WriteLine("METHOD B"); // Iterate through the dictonary using IDictionaryEnumerator IDictionaryEnumerator idictEnum = (IDictionaryEnumerator)myDictonary.GetEnumerator(); while(idictEnum.MoveNext()) { Console.WriteLine("Key: {0}, Value: {1}.", idictEnum.Key, idictEnum.Value); } A 30. IDisposable [DateTime.Now]. Message TEST 3. Dispose Called None of the other two Dispose methods will get called. In the first instance an exception is throw before the call to Dispose and in the second instance setting an object to null will not result in Dispose being called. A 31. Value and Reference Type a) This will output the value 10, because an implicit boxing operation occurs in the assignment of p to refPoint which causes the value of p to be copied. Had the Point struct been declared as a class the value 20 would be returned, because p and refPoint would reference to the same instance on the heap. This process is known as boxing (unboxing is the opposite). b) // Wil return True as same value Console.WriteLine( "Test 1: " + (a == b) ); // Will return true as the call will be delegated to the string equals comparison Console.WriteLine( "Test 2: " + Object.Equals( a, b) ); // Will return False as they are boxes into different objects Console.WriteLine( "Test 3: " + ((object)a == (object)b) ); // Will return True. Even though they are seemingly two different reference types // the literal string "hello" is interned by the compiler. So both references will // point to an interned instance of "hello" (look at String.IsInterned for documentation). Console.WriteLine( "Test 4: " + Object.ReferenceEquals(a, c) ); // Will return true as the same value Console.WriteLine( "Test 5: " + (c == a) ); // Will return true as d is take from the interned pool Console.WriteLine( "Test 6: " + Object.ReferenceEquals(a, d) ); Note, although string is a reference type the equality operators (== and !=) are defined to compare the values of string objects, not references. This was designed to make testing for string equality more intuitive. c) Key thing to notice is that enums are value types. Therefore when assigned to an “object” reference, the value types are boxed onto the heap. Therefore both ‘a’ and ‘b’ are distinct objects on the heap. a == b - False – operators are static methods, so the decision which to call must be made at compile time. Therefore as a and b are of type ‘object’, the compiler will use object.operator==(), which does reference comparison. a.Equals(b) – True – Equals is a virtual method on object which is overridden by value types to provide value type comparison. Object.Equals(a, b) – True – Static method first checks for nulls, then forwards onto the Equals virtual method. Object.ReferenceEquals(a, b) – False – Does what is says on the tin. Part C was supplied by David Walker. A 32. Reference to a Value type This is not possible. C# won't let you get the reference to a value because of the presence of the garbage collector. If you had a reference (aka internal pointer) somewhere into the middle of an array, any movement of the array as part of a GC would mean that the reference would be invalid. Hence any referencing of value types results in a copy. You can however do this using unsafe code: class UnsafePointerExample { ///
/// The main entry point for the application. ///
[STAThread] static void Main(string[] args) { TestStruct t = new TestStruct(); unsafe { TestStruct* pt1 = &t; TestStruct* pt2 = &t; // Set the value of pt1 to 100 pt1->x = 100; // Print the value of pt1 Console.WriteLine(pt1->x); // prints 100 // Print the value of pt2 Console.WriteLine(pt2->x); // prints 100 // Print the value of the actual struct Console.WriteLine(t.x); // prints 100 } Console.ReadLine(); } } public struct TestStruct { public int x; public int y; } A 33. Basic Maths a) If you got 5000 you are wrong, the correct answer is 4100. b) 323. A 34. Logic a) If you answered that you are first, then you are wrong. If you overtake the second person and you take his place, so you are second. b) If you answered that you are second to last, then you are wrong. It is impossible overtake the LAST Person, unless you count lapping them (in which case you will remain in the same position that you were before you lapped them). A 35. Case Statements a) Compiles and writes the number to the console window. b) Does not compile. Although C# does supports fall through cases it does not support falling out of one case block into another. c) Uses an explicit transfer which behaves identically to case a). A 36. Basic Delegates The delegate definition should look like: ///
/// Delegate to call CallOnMe.MyFunction ///
public delegate string CallMyFunctionHandler(string myValue); The code to call the delegate should look like: // Define an instance of the delegate CallMyFunction callFunct = new CallMyFunction( new CallOnMe().MyFunction ); // Invoke the delegate Console.WriteLine( callFunct.DynamicInvoke( new object[]{"My Test Call"} ) ); A 37. Basic Database and ADO Questions a) 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. b) Multiple processes must agree that they will share the same connections, where every parameter is the same, including the security settings. The connection string must be identical. A 38. ASP.NET Basics a) Server-side code executes on the server. Client-side code executes in the context of the clients' browser. b) Session objects, Application objects, ViewState, cookies, hidden form fields. c) It allows page objects to save their state in a Base64 encoded string in the page HTML. One should only have it enabled when needed because it adds to the page size and can get fairly large for complex pages with many controls. (It takes longer to download the page). d) Server.Transfer transfers excution directly to another page. Response.Redirect sends a response to the client and directs the client (the browser) to load the new page (it causes a roundtrip). If you don't need to execute code on the client, Transfer is more efficient. e) Use a State Server or SQL Server to store the session state. f) The Page class. g) (Web Services Description Language). It describes the interfaces and other information of a web service. h) CompareValidator Control i) You must set the DataSource property and call the DataBind method. A 39. Architecture a) N-Tier model answer should include: 1. Presentation (UI). 2. Business (logic and underlying code) . 3. Data (from storage or other sources). b) Commonly used Microsoft Application Blocks are (note, there are others): Exception Management Logging Data Access User Interface Caching Application Block for .NET Asynchronous Invocation Application Block for .NET Configuration Management Application Block for .NET A 40. Basic Locking a) Both sychronisation techniques shown require the callee to explicitly apply locks in order to prevent simultaneous multithreaded access to their underlying collections. b) Neither provide guaranteed method level locking (see a). c) The code to create a synchronised hashtable is: Hashtable hashSync = Hashtable.Synchronized( new Hashtable() ); Doing this removes the needs for locks when adding or removing, since the called collection now handles each call to it. However, even when a collection is synchronized, other threads could still modify the items in it, which will cause any enumerators to throw exceptions. To guarantee thread safety during enumeration you must use a lock. d) In summary SyncRoot is rarely useful, see http://blogs.msdn.com/brada/archive/2003/09/28/50391.aspx for details. A 41. Interfaces Yes the code does compile. The code needed to return the string "Driving my car home" is: IPersonalCar myCar = new MyCar(); string strReturn = myCar.Drive(); A 42. Interfaces Members e. Events A 43. Static Constructors c. A static constructor is called before the first instance of the class is created, or before the first static method is called. A 44. Operators The code will return the following: 1 False 2 True 3 True 4 True 5 True The first result results false, since this tests checks the reference equality of two boxed parameters. All the other tests check for value equality. A 45. Operators You cannot overload the && or || operators, but you can affect how they are evaluated. When the && or || operators are called the C# compiler generates code which calls the true, false and & operators. Overloading these will enable you to customise the behaviour of these operators. A 46. Remoting a) Remoting is a more efficient communication exchange when you can control both ends of the application involved in the communication process. Web Services provide an open-protocol-based exchange of informaion. Web Services are best when you need to communicate with an external organization or another (non-.NET) technology. b) Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed. c) If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode. d) A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease. e) By implementing ILease interface when writing the class code. f) Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred. A 47. Architecture Cyclomatic complexity is the most widely used member of a class of static software metrics. Cyclomatic complexity may be considered a broad measure of soundness and confidence for a program. Introduced by Thomas McCabe in 1976, it measures the number of linearly-independent paths through a program module. This measure provides a single ordinal number that can be compared to the complexity of other programs. Cyclomatic complexity is often referred to simply as program complexity, or as McCabe's complexity. It is often used in concert with other software metrics. As one of the more widely-accepted software metrics, it is intended to be independent of language and language format. A large number of programs have been measured, and ranges of complexity have been established that help the software engineer determine a program's inherent risk and stability. The resulting calibrated measure can be used in development, maintenance, and reengineering situations to develop estimates of risk, cost, or program stability. Studies show a correlation between a program's cyclomatic complexity and its error frequency. A low cyclomatic complexity contributes to a program's understandability and indicates it is amenable to modification at lower risk than a more complex program. A module's cyclomatic complexity is also a strong indicator of its testability (see Test planning under Usage Considerations). Risk Evaluation 1-10 A simple program, without much risk. 11-20 More complex, moderate risk. 21-50 Complex, high risk program > 50 Untestable program (very high risk) A 48. Security Attributes All the relevant information is stored in the asssembly metadata on compilation and based on permissions of the calling code. The CLR will make sure that application or assembly doesn't even get loaded in cases where the callee doesn't have relevant permissions vis a vis Imperative security, where everything is checked in assembly code and assembly will invariably get loaded and executed before it checks for any such issue or lack of permissions. So , benefits of Declarative security are: 1. Inducing efficiency as all relevant information is stored in the metadata. 2. Cleaner code as security is not mixed with program logic it's done cleanly using attributes. A 49. Native Image Cache A native image is a file containing compiled processor-specific machine code. The native image cache is a reserved area of the global assembly cache. Once you create a native image for an assembly, the runtime automatically uses that native image each time it runs the assembly. You do not have to perform any additional procedures to cause the runtime to use a native image. Running Ngen.exe on an assembly allows the assembly to load and execute faster, because it restores code and data structures from the native image cache rather than generating them dynamically using the IL. Topic Notes: The JIT compiler knows precisely which CPU the user has installed in their computer causing the JIT compiler to produce native instructions that are specific to the user's machine. When you use an unmanaged compiler, the compiler usually emits code for an Intel Pentium Pro, Pentium II, Pentium III, or Pentium 4 processor. The JIT compiler knows if the machine has a single CPU or multiple CPUs installed. If a single CPU is installed, certain thread synchronization mechanisms don't have to be employed. When a method is JIT compiled, the compiler emits the native CPU instructions. Some of these instructions contain memory addresses that refer to variables or methods. By contrast, an unmanaged compiler and linker emit native CPU instructions that contain memory addresses when building the resulting file. This file must contain relocation information; if Windows can't load the file at its preferred base address, then the embedded memory addresses are incorrect and they must be fixed-up by the Windows' loader. Dynamic relocation (rebasing) significantly hurts the load time of unmanaged code. The native image that Ngen.exe generates cannot be shared across Application Domains. Therefore, you cannot use Ngen.exe in application scenarios, such as ASP.NET, that require assemblies to be shared across application domains. No Intellectual Property Protection. Many people believe that it might be possible to ship NGen'd files without shipping the files containing the original IL code thereby keeping their intellectual property a secret. Unfortunately, this is not possible. At runtime, the CLR requires access to the assembly's metadata and the NGen'd files do not contain the metadata. NGen'd Files Can Get Out-Of-Sync. When the CLR loads an NGen'd file it compares a number of attributes about the previously-compile code and the current execution environment. If any of the attributes don't match then the NGen'd file cannot be used and the normal JIT compiler process is used instead. Poor Administration. NGen'd file are not automatically deleted when an assembly is uninstalled adversely affecting the .NET Framework's easy administration and XCOPY deployment story. Inferior Load-Time Performance (Rebasing). When Windows loads an NGen'd file, it checks to see if the file loads at its preferred base address. If the file can't load at its preferred base address, then Windows relocates the file, fixing-up all of the memory address references. This is time consuming because Windows must load the entire file into memory and modify various bytes within the file. If you NGen your assemblies it is recommended you explicitly set the base addresses. For server side applications NGen.exe makes no sense, since only the first client request experiences a performance hit; future client requests run at normal speed. A 50. Shallow Copy, Deep Copy and MemberWiseClone A shallow copy creates a new instance of the same type as the original object, and then copies the nonstatic fields of the original object. If the field is a value type, a bit-by-bit copy of the field is performed. If the field is a reference type, the reference is copied but the referred object is not; therefore, the reference in the original object and the reference in the clone point to the same object. In contrast, a deep copy of an object duplicates everything directly or indirectly referenced by the fields in the object. MemberwiseClone method, creates a new instance of the source object and then does a bit-by-bit copy of value types. For reference types, only the reference is copied. As a result both the original object and the clone end-up pointing to the same objects that the original object refers. For example, if X is an object and it references objects Y and Z then a shallow copy A of X will still reference the same Y and Z objects. A 51. This code returns 0 (zero), since the first line of code carries out an integer division which will round down to zero. To perform the calculation as a double do the following: // Use the "d" type marker to denote the values as doubles double expectedValue = 1d/2d; if ( expectedValue > 0 ) { expectedValue = expectedValue + 0.5; } Console.WriteLine(expectedValue); A 52. Control/Component constructors The IContainer constructor is used by non visual components. Controls actually added to a form (eg a Textbox) don't need this constructor since the parent form will automatically call the Dispose method of all the controls in it's Control collection when it is disposed of. However, components which are not added to a form (eg a Timer) won't exist in the form's Control coolection and hence won't automatically have their Dispose method called. Adding these components to the Container object using the IContainer constructor means they will have there Dispose method called. Note, the following code is automatically added to a Windows Form: protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } A 53. Readonly keyword When a field declaration includes a readonly modifier, assignments to the fields can only occur as part of the declaration or in a constructor in the same class. A 54. Events, Timers and GC a) The code will produce the following output: Waiting... Calling GeneralEvent Received GeneralEvent b) If you uncomment the GC.Collect line you will get the following output: Waiting... This is because the GC.Collect assumes that all objects are garbage. It then walks through all the application root objects (eg static objects, local variables and pointers on the thread stack) and builds a graph of all objects reachable from the root objects. Any variables which are not referred to by the application root objects will be collected. A 55. Threading a) Atomic operations are operations that are guaranteed to complete once they begin; ie they cannot be interrupted. The System.Threading.Interlocked class provides several methods that guarantee that it's operations are atomic. Incrementing, decrementing, exchanging and comparing and exchanging are provided as atomic operations. b) It downloads text from a web site (darwins origin of the species) then runs three parallel task. The tasks are described as follows: AA1: Finds the longest word. AA2: Finds the most common word thats greater than 6 characters long. AA3: Finds how many times the word "species" occurs in the text. A 56. Interop using System.Runtime.InteropServices; public delegate int HookDelegate(int uMsg, int wParam, int lParam); [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)] public static extern int SetWindowsHookEx(int idHook, HookDelegate lpfn, int hInstance, int threadId); public static void ExampleCall() { // Declare callback HookDelegate myHook = new HookDelegate(MsgBoxHookProc); // Call API with callback int hHook = SetWindowsHookEx(WH_CBT, myHook, 0, 0); } public static bool MsgBoxHookProc(int nCode, int wParam, int lParam) { // Process callbacks return false; } A 57. SQL Server a) Nothing. The cast error is considered sufficently severe to abort the transaction: Server: Msg 245, Level 16, State 1, Line 9 Syntax error converting the varchar value 'AJB1 ' to a column of data type int. b) The table will contain 'AJB1'. The insert error is NOT considered sufficently severe to abort the transaction: Server: Msg 515, Level 16, State 2, Line 1 Cannot insert the value NULL into column 'TEST', table 'WORM.STPdbo.AJB_TEST'; column does not allow nulls. INSERT fails. The statement has been terminated. (1 row(s) affected) c) You can set SET XACT_ABORT ON, or check @@error - but you have to check it after EVERY SINGLE INSERT. INHO this is another example why you must use Oracle for any critical databases. A 58. General Returns 0, since using f++ returns the current value BEFORE performing the addition operation. A 59. Threading and Memory Barriers a) Will be essentially random in nature, but most likely to contain the last word 4 times (as the data capture is by reference). b) Will be random order, but containing each of the words only once (as the memory barrier will force the order). c) Will be in order containing each of the words only once (as the memory barrier will force the data capture to copy each word in (since a thread time slice is typically just less than 15ms)). A 60. Database Indexes a: 1, 3, 4 b: 2 c: 2, 3
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet