C# Interview Questions and Answers

As a software engineer, I focus on .NET, especially asp.net, C#, WCF and so on, and I am also very interested in Search Engine Optimization.

How to navigate between pages in WPF

WPF supports browser-style navigation when you create stand-alone or browser-based applications. You can use this approach when you want to build applications that require a concept of navigation, such as wizards or help applications. You can navigate from one page to another in two ways: declaratively by using hyperlinks or programmatically by using the NavigationService class.

WPF provides three ways to navigate between pages in an application:

  1. Navigate from one page to another page.
  2. Navigate to a fragment within a page.
  3. Navigate between subcontent frames in a page.

Maintaining State by Using Navigation Services

In WPF, when you navigate away from a page, the page is destroyed; when you go back or forward to a page, the page is re-created. The purpose of this implementation is to save memory. Often, pages are not revisited after they are initially rendered, so the default behavior of WPF is to discard a page after you leave it. However, because any controls on a page that collect data are also created anew, any previous data is lost. Therefore, you may wish to alter the default behavior in WPF to maintain the state of certain pages. You can do this by setting the KeepAlive property in the navigation journal, by using dependency properties, or by implementing the IProvideCustomContentState interface.

Overview of Windows Presentation Foundation

Question 1. You are creating a WPF application by using the Microsoft .NET Framework version 3.5. The application will be executed on client computers that run the Windows Vista operating system without modifying the default security settings. 

You need to ensure that the following requirements are met: 

  • The application can modify files that are located on the local hard drive.
  • The application can add device drivers for a custom peripheral device.
  • The application can restart the computer.

Which application type should you use?

Answer: A WPF stand-alone application can be deployed on client computers that are running Windows Vista and can modify files, add device drivers, and restart the computer without modifying the default security settings.

Question 2. You are creating a WPF stand-alone application by using the .NET Framework 3.5. The application will be used to store membership details for a local library. The application must include a New User dialog box that you can use to create a new membership record. The dialog box will be launched from a toolbar button. 

Which class should you use to create the New User dialog box?

Answer: The Window class is the only class in this list that is designed to create windows and dialog boxes in a WPF application.

Dynamic Type in C# 4.0

Dynamic type is a new type in C# 4.0. Dynamic type is a static type, but an object of type dynamic bypasses static type checking. In most cases, it functions like it has type object. At compile time, an element that is typed as dynamic is assumed to support any operation. Therefore, you do not have to be concerned about whether the object gets its value from a COM API, from a dynamic language such as IronPython and javascript, from the HTML Document Object Model (DOM), from reflection, or from somewhere else in the program. However, if the code is not valid, errors are caught at run time. In another word, an exception will occur.

When you use the dynamic keyword, you are invoking the new Dynamic Language Runtime libraries (DLR) in the .NET framework.  The dynamic language runtime (DLR) is a runtime environment that adds a set of services for dynamic languages to the common language runtime (CLR). The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. Dynamic languages can identify the type of an object at run time instead of compile time, whereas in statically typed languages such as C# when you use option explicit on, you must specify object types at design time. Examples of dynamic languages are Lisp, JavaScript, PHP, Smalltalk, Ruby, Python, ColdFusion, Cobra, and now C#.

Here are main advantages of using DLR

  • Simplifies Porting Dynamic Languages to the .NET Framework
  • Enables Dynamic Features in Statically Typed Languages
  • Provides Future Benefits of the DLR and .NET Framework
  • Enables Sharing of Libraries and Objects
  • Provides Fast Dynamic Dispatch and Invocation

Dynamic Language Runtime Architecture Overview http://jack-fx.com

Now, let’s back to the dynamic type in C#. Here is an example.

we have a class named MyTestClass

   1: class MyTestClass

   2: {

   3:     public MyTestClass()

   4:     {

   5:         Console.WriteLine("constractor with no parameter");

   6:     }

   7:     public MyTestClass(int v)

   8:     {

   9:         Console.WriteLine("constractor with parameter:{0}", v);

  10:     }

  11:  

  12:     public void TestMethod1(int i)

  13:     {

  14:         Console.WriteLine("Test method with parameter:{0}", i);

  15:     }

  16: }

And we can call it like this

   1: dynamic myInstance = new MyTestClass();

   2: myInstance.TestMethod1(101);

It is exactly like the non-dynamic type, but we can use it in this way.

   1: dynamic myInstance = new MyTestClass();

   2: myInstance.nonexistentMethod();

Yes, the nonexistentMethod method doesn’t exist. And you will find there will be no error occurred when compiled. But if you run it, you will get an exception like this

Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ‘C4Test.MyTestClass’ does not contain a definition for ‘nonexistentMethod’

This is the dynamic type in C#, give you the flexibility, and do everything at runtime.

Guidelines for the WPF layout

These are the five most popular layout panels of WPF:

    Grid Panel
    Stack Panel
    Dock Panel
    Wrap Panel
    Canvas Panel

How to use them better, you should follow these guidelines:

  • Avoid fixed positions – use the Alignment properties in combination with Margin to position elements in a panel
  • Avoid fixed sizes – set the Width and Height of elements to Auto whenever possible.
  • Don’t abuse the canvas panel to layout elements. Use it only for vector graphics.
  • Use a StackPanel to layout buttons of a dialog
  • Use a GridPanel to layout a static data entry form. Create a Auto sized column for the labels and a Star sized column for the TextBoxes.
  • Use an ItemControl with a grid panel in a DataTemplate to layout dynamic key value lists. Use the SharedSize feature to synchronize the label widths.

ListView control in ASP.NET

Before ASP.NET 3.5, developers who needed to display a set of records could choose between the GridView, DataList, and Repeater controls. The GridView provides rich data features, but has a very boxy layout; the DataList and Repeater allow for a more flexible layout, but lack the "point and click" data features found in the GridView, DetailsView, and FormView controls. The ListView bridges the gap between layout flexibility and built-in data features. This control provides you with complete control over the markup output sent down to a client – while still providing rich data paging, editing, deleting and insertion semantics.

The ListView control, does not only encase its rendered output with any additional markup, but also responsible for specifying the precise HTML rendered for the ListView control. Here are the ListView’s 11 templates:

  • ItemTemplate
  • AlternatingItemTemplate
  • EmptyItemTemplate
  • EditItemTemplate
  • GroupSeparatorTemplate
  • ItemSeparatorTemplate
  • GroupTemplate
  • EmptyDataTemplate
  • InsertItemTemplate
  • LayoutTemplate
  • SelectedItemTemplate

The ListView control, new to ASP.NET 3.5, offers the same rich data features found in the GridView, but allows for a much more flexible rendered output. As we saw here, the ListView’s rendered output is based on the markup, databinding expressions, and Web controls added to its LayoutTemplate and ItemTemplate. There are a number of other templates available, as well, and we will explore these along with features like sorting, paging, deleting, editing, and inserting in future installments of this article series.

Named Parameters

What is Named Parameters

Named parameters differs from a regular function call in that the values are passed by associating each one with a parameter name, instead of providing an ordered list of values. You can use the named parameters from in C# from 4.0. Besides C#, Ada, Common Lisp, Fortran, Mathematica, Objective-C, PL/SQL, Perl, Python, R, Scala, Smalltalk, Visual Basic are all support the named parameters.

A Demo of Named Parameters

For example, we have a class named Person with a constructor which will received fistName, lastName, and age.

   1: public class Person

   2: {

   3:     public Person(string firstName, string lastName, int age)

   4:     {

   5:         this.FirstName = firstName;

   6:         this.LastName = LastName;

   7:         this.Age = age;

   8:     }

   9:  

  10:     public string FirstName { get; set; }

  11:     public string LastName { get; set; }

  12:     public int Age { get; set; }

  13: }

Using the named parameters, we do not need to call the instructor one by one, but give value with parameters. like this

var person1 = new Person(firstName: "Fx", lastName: "Jack", age: 20);var person2 = new Person(lastName: "Jack", age: 20, firstName: "Fx");var person3 = new Person(lastName: "Jack", firstName: "Fx", age: 20);

and the person1, person2, and person3 are the same indeed.

Benefit of using named parameters

  • makes the code more understandable. 
  • provide the flexibility plus the ‘optional parameters’
  • it can make your code higher quality.

Extension Methods

What is Extension Methods

Extension methods is new in .NET 3.5(Visual Studio 2008), and enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

A demo of extension method

When you are using the StringBuilder, it has methods of AppendLine or AppendFormat, but it is a pit that when you are using AppendLine, you cannot use the format. Here is a demo, that we use the extension method to add our ‘AppendFormatWithLine’ method, and use it as methods given by .Net framework.

   1:  namespace ConsoleApplication2
   2:  {
   3:      class Program
   4:      {
   5:          static void Main(string[] args)
   6:          {
   7:              StringBuilder sbValue = new StringBuilder();
   8:              sbValue.AppendFormatWithLine("Welcome to {0}", "http://jack-fx.com");
   9:   
  10:              Console.WriteLine(sbValue);
  11:          }
  12:      }
  13:   
  14:      public static class StringBuilderExtension
  15:      {
  16:          public static void AppendFormatWithLine(this StringBuilder sb, string format, params object[] args)
  17:          {
  18:              sb.AppendFormat(format, args);
  19:              sb.AppendLine();
  20:          }
  21:      }
  22:  }

You will see, call the extension method ‘AppendFormatWithLine’ is as easy as you can imagine.

Rules and Guidelines to use Extension Methods

  • C# supports extension methods only, and does not offer extension extension operators, properties, extension
    events, and so on.
  • Extension methods must be declared in non-generic, static classes. However, there is no restriction on the name of the class; you can call it whatever you want. Of course, an extension method must have at least one parameter, and only the first parameter can be marked with the this keyword.
  • C# compiler looks only for extension methods defined in static classes that are themselves defined at the file scope. In other words, if you define the static class nested within another class, the C# compiler will emit an error message.
  • Since the static classes can have any name you want, it takes the C# compiler time to find extension methods as it must look at all the file-scope static classes and scan their static methods for a match. To improve performance and also to avoid considering an extension method that you may not want, the C# compiler requires that you “import”extension methods. For example, if someone has defined a StringBuilderExtension
    class in one namespace, then a programmer who wants to have access to this class’s extension methods must put a using namespace; directive at the top of the source code file.
  • It is possible that multiple static classes could define the same extension method. If the compiler detects that two or more extension methods exist, then the compiler issues an error message(error CS0121). To fix this error, you must modify your source code. Specifically, you cannot use the instance method syntax to call this static method anymore; instead you must now use the static method syntax where you explicitly indicate
    the name of the static class to explicitly tell the compiler which method you want to invoke.
  • You should use this feature sparingly, as not all programmers are familiar with it. For example, when you extend a type with an extension method, you are actually extending derived types with this method as well. Therefore, you should not define an extension method whose first parameter is System.Object, as this method will be callable for all expression types and this will really pollute Visual Studio’s IntelliSense window.