Wednesday, 30 March 2011

C# Interview Questions


Good for preparation and general self-testing, but too specific for the actual job interview. This was sent in by a job applicant getting ready to step into the .NET field in India.
  1. Are private class-level variables inherited? - Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.
  2. Why does DllImport not work for me? - All methods marked with the DllImport attribute must be marked as public static extern.
  3. Why does my Windows application pop up a console window every time I run it? - Make sure that the target type set in the project properties setting is set to Windows Application, and not Console Application. If you’re using the command line, compile with /target:winexe, not /target:exe.
  4. Why do I get an error (CS1006) when trying to declare a method without specifying a return type? - If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following is an example: // This results in a CS1006 error public static staticMethod (mainStatic obj) // This will work as wanted public static void staticMethod (mainStatic obj)
  5. Why do I get a syntax error when trying to declare a variable called checked? - The word checked is a keyword in C#.
  6. Why do I get a security exception when I try to run my C# app? - Some security exceptions are thrown if you are working on a network share. There are some parts of the frameworks that will not run if being run off a share (roaming profile, mapped drives, etc.). To see if this is what’s happening, just move the executable over to your local drive and see if it runs without the exceptions. One of the common exceptions thrown under these conditions is System.Security.SecurityException. To get around this, you can change your security policy for the intranet zone, code group 1.2, (the zone that running off shared folders falls into) by using the caspol.exe tool.
  7. Why do I get a CS5001: does not have an entry point defined error when compiling? - The most common problem is that you used a lowercase ‘m’ when defining the Main method. The correct way to implement the entry point is as follows: class test { static void Main(string[] args) {} }
  8. What optimizations does the C# compiler perform when you use the /optimize+ compiler option? - The following is a response from a developer on the C# compiler team: We get rid of unused locals (i.e., locals that are never read, even if assigned). We get rid of unreachable code. We get rid of try-catch with an empty try. We get rid of try-finally with an empty try. We get rid of try-finally with an empty finally. We optimize branches over branches: gotoif A, lab1 goto lab2: lab1: turns into: gotoif !A, lab2 lab1: We optimize branches to ret, branches to next instruction, and branches to branches.
  9. What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname() does not compile)? - The syntax for calling another constructor is as follows: class B { B(int i) { } } class C : B { C() : base(5) // call base constructor B(5) { } C(int i) : this() // call C() { } public static void Main() {} }
  10. What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development? - Try using RegAsm.exe. Search MSDN on Assembly Registration Tool.
  11. What is the difference between a struct and a class in C#? - From language spec: The list of similarities between classes and structs is as follows. Longstructs can implement interfaces and can have the same kinds of members as classes. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.
  12. My switch statement works differently than in C++! Why? - C# does not support an explicit fall through for case blocks. The following code is not legal and will not compile in C#:
13.       switch(x)
14.       {
15.               case 0: // do something
16.               case 1: // do something as continuation of case 0
17.               default: // do something in common with
18.                      //0, 1 and everything else
19.               break;
20.       }
To achieve the same effect in C#, the code must be modified as shown below (notice how the control flows are explicit):
class Test
{
  public static void Main() {
         int x = 3;
         switch(x)
         {
                 case 0: // do something
                 goto case 1;
                 case 1: // do something in common with 0
                 goto default;
                 default: // do something in common with 0, 1, and anything else
                 break;
         }
  }
}
  1. Is there regular expression (regex) support available to C# developers? - Yes. The .NET class libraries provide support for regular expressions. Look at the System.Text.RegularExpressions namespace.
  2. Is there any sample C# code for simple threading? - Yes:
23.       using System;
24.       using System.Threading;
25.       class ThreadTest
26.       {
27.               public void runme()
28.               {
29.                      Console.WriteLine("Runme Called");
30.               }
31.               public static void Main(String[] args)
32.               {
33.                      ThreadTest b = new ThreadTest();
34.                      Thread t = new Thread(new ThreadStart(b.runme));
35.                      t.Start();
36.               }
}
  1. Is there an equivalent of exit() for quitting a C# .NET application? - Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it’s a Windows Forms app.
  2. Is there a way to force garbage collection? - Yes. Set all references to null and then call System.GC.Collect(). If you need to have some objects destructed, and System.GC.Collect() doesn’t seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers().
  3. Is there a way of specifying which block or loop to break out of when working with nested loops? - The easiest way is to use goto:
40.       using System;
41.       class BreakExample
42.       {
43.               public static void Main(String[] args) {
44.                      for(int i=0; i<3; i++)
45.                      {
46.                              Console.WriteLine("Pass {0}: ", i);
47.                              for( int j=0 ; j<100 ; j++ )
48.                              {
49.                                      if ( j == 10)
50.                                             goto done;
51.                                      Console.WriteLine("{0} ", j);
52.                              }
53.                              Console.WriteLine("This will not print");
54.                      }
55.                      done:
56.                              Console.WriteLine("Loops complete.");
57.               }
}
  1. Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace? - There is no way to restrict to a namespace. Namespaces are never units of protection. But if you’re using assemblies, you can use the ‘internal’ access modifier to restrict access to only within the assembly.

Developer C#

A representative of a high-tech company in United Kingdom sent this in today noting that the list was used for interviewing a C# .NET developer. Any corrections and suggestions would be forwarded to the author. I won’t disclose the name of the company, since as far as I know they might still be using this test for prospective employees. Correct answers are in green color.
1) The C# keyword ‘int’ maps to which .NET type?
1.      System.Int16
2.      System.Int32
3.      System.Int64
4.      System.Int128
2) Which of these string definitions will prevent escaping on backslashes in C#?
1.      string s = #”n Test string”;
2.      string s = “’n Test string”;
3.      string s = @”n Test string”;
4.      string s = “n Test string”;

3) Which of these statements correctly declares a two-dimensional array in C#?
1.      int[,] myArray;
2.      int[][] myArray;
3.      int[2] myArray;
4.      System.Array[2] myArray;
4) If a method is marked as protected internal who can access it?
1.      Classes that are both in the same assembly and derived from the declaring class.
2.      Only methods that are in the same class as the method in question.
3.      Internal methods can be only be called using reflection.
4.      Classes within the same assembly, and classes derived from the declaring class.
5) What is boxing?
a) Encapsulating an object in a value type.
b) Encapsulating a copy of an object in a value type.
c) Encapsulating a value type in an object.
d) Encapsulating a copy of a value type in an object.
6) What compiler switch creates an xml file from the xml comments in the files in an assembly?
1.      /text
2.      /doc
3.      /xml
4.      /help
7) What is a satellite Assembly?
1.      A peripheral assembly designed to monitor permissions requests from an application.
2.      Any DLL file used by an EXE file.
3.      An assembly containing localized resources for another assembly.
4.      An assembly designed to alter the appearance or ‘skin’ of an application.
8) What is a delegate?
1.      A strongly typed function pointer.
2.      A light weight thread or process that can call a single method.
3.      A reference to an object in a different process.
4.      An inter-process message channel.
9) How does assembly versioning in .NET prevent DLL Hell?
1.      The runtime checks to see that only one version of an assembly is on the machine at any one time.
2.      .NET allows assemblies to specify the name AND the version of any assemblies they need to run.
3.      The compiler offers compile time checking for backward compatibility.
4.      It doesn’t.
10) Which “Gang of Four” design pattern is shown below?
public class A {
    private A instance;
    private A() {
    }
    public
static
A Instance {
        get
        {
            if ( A == null )
                A = new A();
            return instance;
        }
    }
}
1.      Factory
2.      Abstract Factory
3.      Singleton
4.      Builder
11) In the NUnit test framework, which attribute must adorn a test class in order for it to be picked up by the NUnit GUI?
1.      TestAttribute
2.      TestClassAttribute
3.      TestFixtureAttribute
4.      NUnitTestClassAttribute
12) Which of the following operations can you NOT perform on an ADO.NET DataSet?
1.      A DataSet can be synchronised with the database.
2.      A DataSet can be synchronised with a RecordSet.
3.      A DataSet can be converted to XML.
4.      You can infer the schema from a DataSet.
13) In Object Oriented Programming, how would you describe encapsulation?
1.      The conversion of one type of object to another.
2.      The runtime resolution of method calls.
3.      The exposition of data.
4.      The separation of interface and implementation.
The question number 10 isn’t correct. The class given in the question can’t be created under any circumstances. The c’tor in private so no instance can be created and the Instance() func isn’t static, so it can’t be called without instance of the class. It’s Singleton pattern only if the Instance() func is static and private member A is static too.
Question 10 is incorrect. To create a Singleton class, question 10 should be changed as follows:
public class A
{
static private A instance;
private A()
{
}
static public A GetInstance()
{
if ( instance == null )
instance = new A();
return instance;
}
}
Question 3) has two correct answers (jagged array is second)
3) Which of these statements correctly declares a two-dimensional array in C#?
int[,] myArray;
int[][] myArray;
and Question 10) has a more shorter code:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}

public class A
{
private static A instance;
private A()
{
}
public static A Instance
{
get
{
if (instance == null)
instance = new A();
return instance;
}
}
}
[…] Dot Net Interview Questions The ability to do something does not imply that you can explain it conceptually, or even that you understand the concept of what you are doing. So I have prepared a list of questionstasks that I think would be useful to complete before going for a C# related job. I have also provided a separate page with questions AND answers for the first set of 173 questions, and another page for the answers to the rest of the questions (not including Scott’s questions). You can find the first link below the first set of questions and the second link at the bottom of the post - they are also directly below if you want to jump straight to them. Rule 1 - Don’t say to yourself “yeah I know that” and move on to the next question. Answer the question as if you were in an interview. Rule 2 - For the questions that require code - write the code yourself on a piece of paper, don’t use an IDE. The QuestionsTasks: Name 10 C# keywords. What is public accessibility? What is protected accessibility? What is internal accessibility? What is protected internal accessibility? What is private accessibility? What is the default accessibility for a class? What is the default accessibility for members of an interface? What is the default accessibility for members of a struct? Can the members of an interface be private? Methods must declare a return type, what is the keyword used when nothing is returned from the method? Class methods to should be marked with what keyword? Write some code using interfaces, virtual methods, and an abstract class. A class can have many mains, how does this work? Does an object need to be made to run main? Write a hello world console application. What are the two return types for main? What is a reference parameter? What is an out parameter? Write code to show how a method can accept a varying number of parameters. What is an overloaded method? What is recursion? What is a constructor? If I have a constructor with a parameter, do I need to explicitly create a default constructor? What is a destructor? Can you use access modifiers with destructors? What is a delegate? Write some code to use a delegate. What is a delegate useful for? What is an event? Are events synchronous of asynchronous? Events use a publisher/subscriber model. What is that? Can a subscriber subscribe to more than one publisher? What is a value type and a reference type? Name 5 built in types. string is an alias for what? Is string Unicode, ASCII, or something else? Strings are immutable, what does this mean? Name a few string properties. What is boxing and unboxing? Write some code to box and unbox a value type. What is a heap and a stack? What is a pointer? What does new do in terms of objects? How do you dereference an object? In terms of references, how do == and != (not overridden) work? What is a struct? Describe 5 numeric value types ranges. What is the default value for a bool? Write code for an enumeration. Write code for a case statement. Is a struct stored on the heap or stack? Can a struct have methods? What is checked { } and unchecked { }? Can C# have global overflow checking? What is explicit vs. implicit conversion? Give examples of both of the above. Can assignment operators be overloaded directly? What do operators is and as do? What is the difference between the new operator and modifier? Explain sizeof and typeof. What does the stackalloc operator do? Contrast ++count vs. count++. What are the names of the three types of operators? An operator declaration must include a public and static modifier, can it have other modifiers? Can operator parameters be reference parameters? Describe an operator from each of these categories: Arithmetic Logical (boolean and bitwise) String concatenation Increment, decrement Shift Relational Assignment Member access Indexing Cast Conditional Delegate concatenation and removal Object creation Type information Overflow exception control Indirection and Address What does operator order of precedence mean? What is special about the declaration of relational operators? Write some code to overload an operator. What operators cannot be overloaded? What is an exception? Can C# have multiple catch blocks? Can break exit a finally block? Can continue exit a finally block? Write some try…catch…finally code. What are expression and declaration statements? A block contains a statement list {s1;s2;} what is an empty statement list? Write some if… else if… code. What is a dangling else? Is switch case sensitive? Write some code for a for loop. Can you have multiple control variables in a for loop? Write some code for a while loop. Write some code for do… while. Write some code that declares an array on ints, assigns the values: 0,1,2 to that array and use a foreach to do something with those values. Write some code for a collection class. Describe Jump statements: break, continue, and goto. How do you declare a constant? What is the default index of an array? What is array rank? Can you resize an array at runtime? Does the size of an array need to be defined at compile time. Write some code to implement a multidimensional array. Write some code to implement a jagged array. What is an ArrayList? Can an ArrayList be ReadOnly? Write some code that uses an ArrayList. Write some code to implement an indexer. Can properties have an access modifier? Can properties hide base class members of the same name? What happens if you make a property static? Can a property be a ref or out parameter? Write some code to declare and use properties. What is an accessor? Can an interface have properties? What is early and late binding? What is polymorphism What is a nested class? What is a namespace? Can nested classes use any of the 5 types of accessibility? Can base constructors can be private? object is an alias for what? What is reflection? What namespace would you use for reflection? What does this do? Public Foo() : this(12, 0, 0) Do local values get garbage collected? Is object destruction deterministic? Describe garbage collection (in simple terms). What is the using statement for? How do you refer to a member in the base class? Can you derive from a struct? Does C# supports multiple inheritance? All classes derive from what? Is constructor or destructor inheritance explicit or implicit? What does this mean? Can different assemblies share internal access? Does C# have “friendship”? Can you inherit from multiple interfaces? In terms of constructors, what is the difference between: public MyDerived() : base() an public MyDerived() in a child class? Can abstract methods override virtual methods? What keyword would you use for scope name clashes? Can you have nested namespaces? What are attributes? Name 3 categories of predefined attributes. What are the 2 global attributes. Why would you mark something as Serializable? Write code to define and use your own custom attribute. List some custom attribute scopes and possible targets. List compiler directives? What is a thread? Do you spin off or spawn a thread? What is the volatile keyword used for? Write code to use threading and the lock keyword. What is Monitor? What is a semaphore? What mechanisms does C# have for the readers, writers problem? What is Mutex? What is an assembly? What is a DLL? What is an assembly identity? What does the assembly manifest contain? What is IDLASM used for? Where are private assemblies stored? Where are shared assemblies stored? What is DLL hell? In terms of assemblies, what is side-by-side execution? Name and describe 5 different documentation tags. What is unsafe code? What does the fixed statement do? How would you read and write using the console? Give examples of hex, currency, and fixed point console formatting. Given part of a stack trace: aspnet.debugging.BadForm.Page_Load(Object sender, EventArgs e) +34. What does the +34 mean? Are value types are slower to pass as method parameters? How can you implement a mutable string? What is a thread pool? Describe the CLR security model. What’s the difference between camel and pascal casing? What does marshalling mean? What is inlining? List the differences in C# 2.0. What are design patterns? Describe some common design patterns. What are the different diagrams in UML? What are they used for? Ok, so you’ve done them and you want more? 
 From constructor to destructor (taking into consideration Dispose() and the concept of non-deterministic finalization), what the are events fired as part of the ASP.NET System.Web.UI.Page lifecycle. Why are they important? What interesting things can you do at each? What are ASHX files? What are HttpHandlers? Where can they be configured? What is needed to configure a new extension for use in ASP.NET? For example, what if I wanted my system to serve ASPX files with a *.jsp extension? What events fire when binding data to a data grid? What are they good for? Explain how PostBacks work, on both the client-side and server-side. How do I chain my own JavaScript into the client side without losing PostBack functionality? How does ViewState work and why is it either useful or evil? What is the OO relationship between an ASPX page and its CS/VB code behind file in ASP.NET 1.1? in 2.0? What happens from the point an HTTP request is received on a TCP/IP port up until the Page fires the On_Load event? How does IIS communicate at runtime with ASP.NET? Where is ASP.NET at runtime in IIS5? IIS6? What is an assembly binding redirect? Where are the places an administrator or developer can affect how assembly binding policy is applied? Compare and contrast LoadLibrary(), CoCreateInstance(), CreateObject() and Assembly.Load(). Second .NET Post (What Great .NET Developers Ought To Know): Everyone who writes code Describe the difference between a Thread and a Process? What is a Windows Service and how does its lifecycle differ from a “standard” EXE? What is the maximum amount of memory any single process on Windows can address? Is this different than the maximum virtual memory for the system? How would this affect a system design? What is the difference between an EXE and a DLL? What is strong-typing versus weak-typing? Which is preferred? Why? Corillian’s product is a “Component Container.” Name at least 3 component containers that ship now with the Windows Server Family. What is a PID? How is it useful when troubleshooting a system? How many processes can listen on a single TCP/IP port? What is the GAC? What problem does it solve? Mid-Level .NET Developer Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming. Describe what an Interface is and how it’s different from a Class. What is Reflection? What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP? Are the type system represented by XmlSchema and the CLS isomorphic? Conceptually, what is the difference between early-binding and late-binding? Is using Assembly.Load a static reference or dynamic reference? When would using Assembly.LoadFrom or Assembly.LoadFile be appropriate? What is an Asssembly Qualified Name? Is it a filename? How is it different? Is this valid? Assembly.Load(”foo.dll”); How is a strongly-named assembly different from one that isn’t strongly-named? Can DateTimes be null? What is the JIT? What is NGEN? What are limitations and benefits of each? How does the generational garbage collector in the .NET CLR manage object lifetime? What is non-deterministic finalization? What is the difference between Finalize() and Dispose()? How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization? What does this useful command line do? tasklist /m “mscor*” What is the difference between in-proc and out-of-proc? What technology enables out-of-proc communication in .NET? When you’re running a component within ASP.NET, what process is it running within on Windows XP? Windows 2000? Windows 2003? Senior Developers/Architects What’s wrong with a line like this? DateTime.Parse(myString); What are PDBs? Where must they be located for debugging to work? What is cyclomatic complexity and why is it important? Write a standard lock() plus “double check” to create a critical section around a variable access. What is FullTrust? Do GAC’ed assemblies have FullTrust? What benefit does your code receive if you decorate it with attributes demanding specific Security permissions? What does this do? gacutil /l find /i “Corillian” What does this do? sn -t foo.dll What ports must be open for DCOM over a firewall? What is the purpose of Port 135? Contrast OOP and SOA. What are tenets of each? How does the XmlSerializer work? What ACL permissions does a process using it require? Why is catch(Exception) almost always a bad idea? What is the difference between Debug.Write and Trace.Write? When should each be used? What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not? Does JITting occur per-assembly or per-method? How does this affect the working set? Contrast the use of an abstract base class against an interface? What is the difference between a.Equals(b) and a == b? In the context of a comparison, what is object identity versus object equivalence? How would one do a deep copy in .NET? Explain current thinking around IClonable. What is boxing? Is string a value type or a reference type? What is the significance of the “PropertySpecified” pattern used by the XmlSerializer? What problem does it attempt to solve? Why are out parameters a bad idea in .NET? Are they? Can attributes be placed on specific parameters to a method? Why is this useful? C# Component Developers Juxtapose the use of override with new. What is shadowing? Explain the use of virtual, sealed, override, and abstract. Explain the importance and use of each component of this string: Foo.Bar, Version=2.0.205.0, Culture=neutral, PublicKeyToken=593777ae2d274679d Explain the differences between public, protected, private and internal. What benefit do you get from using a Primary Interop Assembly (PIA)? By what mechanism does NUnit know what methods to test? What is the difference between: catch(Exception e){throw e;} and catch(Exception e){throw;} What is the difference between typeof(foo) and myFoo.GetType()? Explain what’s happening in the first constructor: public class c{ public c(string a) : this() {;}; public c() {;} } How is this construct useful? What is this? Can this be used within a static method? ASP.NET (UI) Developers Describe how a browser-based Form POST becomes a Server-Side event like Button1_OnClick. What is a PostBack? What is ViewState? How is it encoded? Is it encrypted? Who uses ViewState? What is the element and what two ASP.NET technologies is it used for? What three Session State providers are available in ASP.NET 1.1? What are the pros and cons of each? What is Web Gardening? How would using it affect a design? Given one ASP.NET application, how many application objects does it have on a single proc box? A dual? A dual with Web Gardening enabled? How would this affect a design? Are threads reused in ASP.NET between reqeusts? Does every HttpRequest get its own thread? Should you use Thread Local storage with ASP.NET? Is the [ThreadStatic] attribute useful in ASP.NET? Are there side effects? Good or bad? Give an example of how using an HttpHandler could simplify an existing design that serves Check Images from an .aspx page. What kinds of events can an HttpModule subscribe to? What influence can they have on an implementation? What can be done without recompiling the ASP.NET Application? Describe ways to present an arbitrary endpoint (URL) and route requests to that endpoint to ASP.NET. Explain how cookies work. Give an example of Cookie abuse. Explain the importance of HttpRequest.ValidateInput()? What kind of data is passed via HTTP Headers? Juxtapose the HTTP verbs GET and POST. What is HEAD? Name and describe at least a half dozen HTTP Status Codes and what they express to the requesting client. How does if-not-modified-since work? How can it be programmatically implemented with ASP.NET?Explain <@OutputCache%> and the usage of VaryByParam, VaryByHeader. How does VaryByCustom work? How would one implement ASP.NET HTML output caching, caching outgoing versions of pages generated via all values of q= except where q=5 ? Developers using XML What is the purpose of XML Namespaces? When is the DOM appropriate for use? When is it not? Are there size limitations? What is the WS-I Basic Profile and why is it important? Write a small XML document that uses a default namespace and a qualified (prefixed) namespace. Include elements from both namespace. What is the one fundamental difference between Elements and Attributes? What is the difference between Well-Formed XML and Valid XML? How would you validate XML using .NET? Why is this almost always a bad idea? When is it a good idea? myXmlDocument.SelectNodes(”//mynode”); Describe the difference between pull-style parsers (XmlReader) and eventing-readers (Sax) What is the difference between XPathDocument and XmlDocument? Describe situations where one should be used over the other. What is the difference between an XML “Fragment” and an XML “Document.” What does it meant to say “the canonical” form of XML? Why is the XML InfoSet specification different from the Xml DOM? What does the InfoSet attempt to solve? Contrast DTDs versus XSDs. What are their similarities and differences? Which is preferred and why? Does System.Xml support DTDs? How? Can any XML Schema be represented as an object graph? Vice versa? Had enough yet? Here are some more general .NET questions: What is MSIL? What is the CLR and how is it different from a JVM? What is WinFX? What is Indigo? Explain the Remoting architecture. How would you write an asynchronous webservice? What is the Microsoft Enterprise Library? Discuss System.Collections Discuss System.Configuration Discuss System.Data Discuss System.Diagnostics Discuss System.DirectoryServcies Discuss System.Drawing Discuss System.EnterpriseServices Discuss System.Globalization Discuss System.IO Discuss System.Net System.Runtime contains System.Runtime.CompilerServcies, what else? Discuss System.Security Discuss System.Text Discuss System.Threading Discuss System.Web Discuss System.Windows.Forms Discuss System.XML Does VS.NET 2003 have a web browser (think about it)? How are VB.NET and C# different? Contrast .NET with J2EE. What benefit do you have by implementing IDisposable interface in .NET? Explain the difference between Application object and Session object in ASP.NET. Explain the difference between User controls and Custom controls in ASP.NET. Describe transaction control in ADO.NET. Describe transaction control in SQL Server. In .NET, what is an application domain? In SQL Server, what is an index? What is optimistic vs. pessimistic locking? What is the difference between a clustered and non-clustered index. In terms of remoting what is CAO and SAO? Remoting uses MarshallByRefObject, what does this mean? Write some code to use reflection, remoting, threading, and thread synchronization. If the interest is high enough I’ll publish the answers to the rest of these questions (i.e. Scott’s questions) in a future post. Please comment with any extra questions that you think should be added to this list, or any answers for the original 173 that are wrong or incomplete. Ah, what the hell - Misc Can you prevent your class from being inherited by another class? Explain the three tier or n-Tier model. What is SOA? Is XML case-sensitive? Can you explain some differences between an ADO.NET Dataset and an ADO Recordset? (Or describe some features of a Dataset). ASP.NET Explain the differences between Server-side and Client-side code? What does the “EnableViewState” property do? Why would I want it on or off? What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other? What base class do all Web Forms inherit from? What does WSDL stand for? What does it do? Which WebForm Validator control would you use if you needed to make sure the values in two different WebForm controls matched? 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? What is a satellite Assembly? In Object Oriented Programming, how would you describe encapsulation? More questions! Can you store multiple data types in System.Array? What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? How can you sort the elements of the array in descending order? What’s the .NET collection class that allows an element to be accessed using a unique key? What class is underneath the SortedList class? Will the finally block get executed if an exception has not occurred?­ Can you prevent your class from being inherited by another class? If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor? What’s a multicast delegate? What’s the difference between // comments, /* */ comments and /// comments? How do you generate documentation from the C# file commented properly with a command-line compiler? What debugging tools come with the .NET SDK? What does assert() method do? What’s the difference between the Debug class and Trace class? Why are there five tracing levels in System.Diagnostics.TraceSwitcher? Where is the output of TextWriterTraceListener redirected? How do you debug an ASP.NET Web application? What are three test cases you should go through in unit testing? Can you change the value of a variable while debugging a C# application? What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? What is the wildcard character in SQL? Explain ACID rule of thumb for transactions. Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted? What are the ways to deploy an assembly? What namespaces are necessary to create a localized application? What is the smallest unit of execution in .NET? Ok - that’s me done - 
What is a delegate?
answer :
A reference to an object in a different process
i want the difference between trace.write & debug.write?
can any one help me regarding?
2)suppose i am my project as three forms let it be form1 , form2 and form3
i am calling form2 from from1 so how can the form2 can know that form1 is calling?

Useful for preparation, but too specific to be used in the interview.

  1. Is it possible to inline assembly or IL in C# code? - No.
  2. Is it possible to have different access modifiers on the get/set methods of a property? - No. The access modifier on a property applies to both its get and set accessors. What you need to do if you want them to be different is make the property read-only (by only providing a get accessor) and create a private/internal set method that is separate from the property.
  3. Is it possible to have a static indexer in C#? - No. Static indexers are not allowed in C#.
  4. If I return out of a try/finally in C#, does the code in the finally-clause run? - Yes. The code in the finally always runs. If you return out of the try block, or even if you do a “goto” out of the try, the finally block always runs:
5.                 using System; 
6.                  
7.                 class main
8.                 {
9.                         public static void Main()
10.                     {
11.                            try
12.                            {
13.                                    Console.WriteLine("In Try block");
14.                                    return;
15.                            }
16.                            finally
17.                            {
18.                                    Console.WriteLine("In Finally block");
19.                            }
20.                     }
} 
Both “In Try block” and “In Finally block” will be displayed. Whether the return is in the try block or after the try-finally block, performance is not affected either way. The compiler treats it as if the return were outside the try block anyway. If it’s a return without an expression (as it is above), the IL emitted is identical whether the return is inside or outside of the try. If the return has an expression, there’s an extra store/load of the value of the expression (since it has to be computed within the try block).
  1. I was trying to use an “out int” parameter in one of my functions. How should I declare the variable that I am passing to it? - You should declare the variable as an int, but when you pass it in you must specify it as ‘out’, like the following: int i; foo(out i); where foo is declared as follows: [return-type] foo(out int o) { }
  2. How does one compare strings in C#? - In the past, you had to call .ToString() on the strings when using the == or != operators to compare the strings’ values. That will still work, but the C# compiler now automatically compares the values instead of the references when the == or != operators are used on string types. If you actually do want to compare references, it can be done as follows: if ((object) str1 == (object) str2) { … } Here’s an example showing how string compares work:
23.using System;
24.public class StringTest
25.{
26.  public static void Main(string[] args)
27.  {
28.         Object nullObj = null; Object realObj = new StringTest();
29.         int i = 10;
30.         Console.WriteLine("Null Object is [" + nullObj + "]n"
31.                 + "Real Object is [" + realObj + "]n"
32.                 + "i is [" + i + "]n");
33.                 // Show string equality operators
34.         string str1 = "foo";
35.         string str2 = "bar";
36.         string str3 = "bar";
37.         Console.WriteLine("{0} == {1} ? {2}", str1, str2, str1 == str2 );
38.         Console.WriteLine("{0} == {1} ? {2}", str2, str3, str2 == str3 );
39.  }
40.}
Output:
Null Object is []
Real Object is [StringTest]
i is [10]
foo == bar ? False
bar == bar ? True
  1. How do you specify a custom attribute for the entire assembly (rather than for a class)? - Global attributes must appear after any top-level using clauses and before the first type or namespace declarations. An example of this is as follows:
42.using System;
43.[assembly : MyAttributeClass] class X {}
Note that in an IDE-created project, by convention, these attributes are placed in AssemblyInfo.cs.
  1. How do you mark a method obsolete? -
[Obsolete] public int Foo() {...}
or
[Obsolete("This is a message describing why this method is obsolete")] public int Foo() {...}
Note: The O in Obsolete is always capitalized.
  1. How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#? - You want the lock statement, which is the same as Monitor Enter/Exit:
46.lock(obj) { // code }
translates to
try {
  CriticalSection.Enter(obj);
  // code
}
finally
{
  CriticalSection.Exit(obj);
}
  1. How do you directly call a native function exported from a DLL? - Here’s a quick example of the DllImport attribute in action:
48.using System.Runtime.InteropServices; 
49.class C
50.{
51.  [DllImport("user32.dll")]
52.  public static extern int MessageBoxA(int h, string m, string c, int type);
53.  public static int Main()
54.  {
55.         return MessageBoxA(0, "Hello World!", "Caption", 0);
56.  }
57.}
This example shows the minimum requirements for declaring a C# method that is implemented in a native DLL. The method C.MessageBoxA() is declared with the static and external modifiers, and has the DllImport attribute, which tells the compiler that the implementation comes from the user32.dll, using the default name of MessageBoxA. For more information, look at the Platform Invoke tutorial in the documentation.
  1. How do I simulate optional parameters to COM calls? - You must use the Missing class and pass Missing.Value (in System.Reflection) for any values that have optional parameters.

No comments:

Post a Comment