Extension methods, Advantages, Best Practices

18. May 2011

 

What is Extension Method?

Extension methods allow developers to add new methods to the public contract of an existing type, without having to sub-class it or recompile the original type. It allows static methods to be invoked on instance variables. Extension methods can be defined on classes, structures and interfaces.

These methods must take at least one parameter, which represents the instance the method is to operate on. For example, in C#, this is done by using the modifier on such a parameter, when defining the method: 

public static bool IsPalindrome(this string s)
{
      //implementation follows here
}

This example allows one to write, for example:

“some string”.IsPalindrome();

 

Advantages:

  • Cleaner and readable code. LINQ benefits greatly from extension methods as LINQ queries would be almost unreadable without them.
  • Extend functionality on third party objects and sealed classes.
  • Intellisense support. When you add an extension method M on type T, you get 'M' in T's intellisense list (assuming the extension class is in-scope). This make 'M' much easier to find than StaticClass.M(T,...)
  • Create default functionality for interfaces without having to implement an abstract class

 

Disadvantage:

  • There's no compiler error or warning if you have a regular method and an extension method with the same signature in the context.
  • Object and the extension method are versioned independently. You can be put in a trouble when vendor of a class you are extending on creates the method with the same name.
  • You have an extension method and another library creates an extension method with the same signature? You will end up with difficulties in using both namespaces.
  • You can only have extension methods, not properties, indexers, operators, constructors etc.

 

Best practice:

  • Put extension methods into their own namespace. By putting extension methods into their own namespace you enable consumers to include or exclude them separately from the rest of your library. This makes them pluggable.
  • Avoid defining extension methods on System.Object, unless absolutely necessary. When doing so, be aware that VB users will not be able to use thus-defined extension.
  • Think twice before extending types you don't own. The types can include methods with the same name any time.
  • Avoid redefining extension methods on a type T with extension methods on the same type.
  • Use extension methods :
    • To provide helper functionality relevant to every implementation of an interface. 
    • To provide extension to a library that cannot be extended in other way and on which you do not have access over
    • To use with Interfaces. Interfaces cannot include behavior by default. But now you can add it with Extension Methods

 

.Net, c# , ,

WPF : Not Using StringFormat when the data is null.

21. March 2011

 

When you are using StringFormat in XAML, if the data is null, the oputput will be just the format text.

For example, consider the following example.

 

<TextBlock Text="{Binding Path=Amount, StringFormat=Total: {0:C}}" />

 

When the Amount is null, the output of the above binding will be "Total:" This doesn't makes any sense. So, most of teh cases, you have to hide the text or display alternative text. You can achive this with converters (IValueConverter).

There is another simple way to do it without writing any C# code using TargetNullValue. Here is how you can achieve the result.

<TextBlock Text="{Binding Path=Amount,  
TargetNullValue={x:Static System:String.Empty},  
StringFormat=Total: {0:C}}" />

Note:-

If you are using TargetNullValue in Binding, if the value is null, it will ignore the StringFormat. In some cases, you might want to display the Text with formatted string. In this case, you cannot use the above mentioned method. you have to implement your converter.

.Net Tips, .Net, wpf , ,

What is MVVM? and Why MVVM?

2. March 2011

 

 

What is MVVM?

    Model-View-ViewModel (aka Presentation Model), provides architectural solution for the Aplication with UI with complex interdependent interactions.

    Separate the UI(View) from the UI logic using a ViewModel that encapsulates the interactions and provides properties for a View to retrieve its state (and the state of its elements). 

 

Why MVVM?

1. Separates UI from Model. If model needs to change, it can without changing the view and vice versa.

2. Avoids duplicated code to update views.

3. Unit testable UI logic.

4. You can use a 'viewmodel' to aggregate parts of your model that exist in separate classes/libraries to facilitate a more fluent interface for the 'view' to deal with.

5. Data-binding support with INotifyPropertyChanged, ICommand and IvalueConverters

6. Easy to refactor

7. Extensibility.

 

interview questions, .Net, wpf ,

What is WPF and Why WPF?

2. March 2011

What is WPF?

 

    The Windows Presentation Foundation (WPF) is Microsofts next generation UI framework to create applications with a rich user experience. It is part of the .NET framework 3.0 and higher. 

 

Why WPF?

1. Ability to separate UI from logic effectively.

2. Powerfull Data binding, much better than with the WinForms application.

3. Inbuilt animation and storyboarding models.

4. UI virtualisation feature to handle large set of data.

5. Flexible modelling of data on UI with data and control templates.

6. 3D graphics.

7. Video, 3D content and animations support.

8. Declarative UI programming.

9. Rich Event support with routed Events.

 

.Net, interview questions ,

VS 2008 Disable XAML Design View and Always load in full XAML View

28. September 2010

    Most of the developers don't like the XAML design view in VS 2008 as it takes long time to load the desin view and some times it will crash the visual studio also.

The design view can be disabled in visual studio 2008.

1. Go to Tools-Options in menu.

2. Select Text Editor -> XAML -> Miscellaneous node in the popup.

3. Check the 'Always open documents in full XAML view' checkbox.

 

Even if this is not improving load time , try this option.

Hope It helps.

 

.Net Tips, .Net, wpf , ,

VS Tip : Make Solution Explorer always select the currently opened file

10. August 2010

 

Find yourself working in solution with multiple projects and having trouble in selecting the currently opened file in Solution explorer. Here is the solution to automatically select the current item in the solution explorer.

On the Tools -> Options -> Projects and Solutions -> General page, select "Track Active Item in Solution Explorer".  

When enabled, this will sync your solution explorer with the open document. 

 

English, Technical, .Net ,

Visual studio tip - Incremental Search

6. August 2010

Normal Search:

To search for a particular text, usually you have to press CTRL+F and type the complete string and the browse through the results.

 

Disadvantage of this normal search :

  • It's a dialog.
  • There's no indication whether your search term matches anything until you type the complete search term and press return or click Find.
  • If you just mistyped a search term in a 5 megabyte text file, you have to keep waiting for the search to complete.

 

Incremental search:

Incremental search is the one that we can find in latest browsers like Firefox, chrome. Visual studio also has the search functionality like Firefox’s incremental search.

Press the short cut CTRL+I, and start typing the text you are looking for.  The code editor will move around as you type in and find any instance of the text you type in.

CTRL + I initiates the search in the forward direction from the current location (top to bottom).

CTRL+Shift+I reverses the incremental search, or switches a forward search to a reverse search (Bottom to top).

Incremental search can also be initiated using the menu, Edit -> Advanced -> Incremental Search.

 

Case Sensitive Incremental Search :

Incremental search also remebers the  Match case option in the Normal find dialog.

 

Shortcuts:

Move to the next match in the file : CTRL+I

Reverse the direction of the search : CTRL+SHIFT+I

Remove a character from the search string : BACKSPACE

Stop the incremental search      : ESC

 

Advantages:

  • There are no dialogs in incremental search interface, where the interactive search indicator is a cursor position change after you press CTRL+I and start typing the keyword.
  •  Less time required to search.  The search activates as soon as you type the first character. You know immediately when you've got a good the correct match and you can stop typing.
  • If you mistype something, you'll know that immediately, too. Press backspace to correct the typo and you're back to the previous match.

 

Disadvantages:

  • Incremental search doesn't look for text in hidden regions, but a regular search does it.
  • You cannot use wildcards or regular expressions in search strings for incremental searches.

 


 

English, Technical, .Net , ,

Visual Studio crashing on XAML Design view

4. August 2010

    If you're working with XAML in Visual Studio 2008 (SP1), either for WPF or Silverlight, you might have encountered the visual studio crashing problem when opening XAML in design view.

    The first thing to do is to get rid of the design view, if you dont need it frequently. The design view takes long time to open if XAML is complex and sometimes it is useless too.

If you try to edit the XAML file as an XML file, this will disabled IntelliSense, for some reason. So the XML editor was not an option.

alternatively, you can use the "Source Code (Text) Editor". It doesn't seem obvious based on its name, but this editor provides XAML IntelliSense, XML collapsing, and the XAML context menu.

To use this:

  • Right-click on a XAML file in the Solution Explorer
  • Select "Open With..."
  • Select "Source Code (Text) Editor"
  • Click on "Set as Default"
  • Click OK

done!

  If you want to use the default XAML editor (with its split view, navigator, etc.), you just have to select "View Designer" in the text editor's context menu or use SHIFT+F7.

 

.Net, wpf , ,

Missing New Project templates in visual studio

28. July 2010

Recently, I have installed few add-ins to my visual studio. After that I found

1. In add new Items dialog , I found that all the template are missing.

2. In Add new project dialog, all the project templates are also missing.

I have googled for this problem and found that the following command solves this problem

Open visual studio command prompt and execute the command devenv /installvstemplates

This command registers project or item templates that are located in <VisualStudioInstallDir>\Common7\IDE\ProjectTemplates or <VisualStudioInstallDir>\Common7\IDE\ItemTemplates so they can be accessed through the New Project and Add New Item dialog boxes.

Even if the above command didn't solve the problem, try to run the same command after uninstalling all the visual studio add-ins.

·     If you are running visual studio in vista are windows 7, you have to run the visual studio command prompt as administrator.

·     If you are running the 64 bit version, you need to open the x64 Win64 command prompt to run this command.

 

English, Technical, .Net ,