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.

Entries for April, 2011

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.