Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Instant .NET 4.5 Extension Methods How-to
  • Table Of Contents Toc
Instant .NET 4.5 Extension Methods How-to

Instant .NET 4.5 Extension Methods How-to

By : Shawn Ricardo Mclean
4.4 (5)
close
close
Instant .NET 4.5 Extension Methods How-to

Instant .NET 4.5 Extension Methods How-to

4.4 (5)
By: Shawn Ricardo Mclean

Overview of this book

.NET extension methods is an essential feature to know and understand for all .NET developers. Usage of extension methods is found in applications ranging from small to large scale enterprise systems built using the .NET framework. Create and use extension methods the correct way to save your development time and maintainability costs. Instant .NET 4.5 Extension Methods How-to is a practical, hands-on guide that provides you with a number of clear, step-by-step exercises that will help you take advantage of the real power that is behind extension methods and gives you good knowledge of how to use them in your .NET applications. This book covers how to create, write, and use different types of extension methods. It will take you through a number of clear, practical recipes that will help you take advantage of the power of extension methods in the quickest possible way. You will also learn exactly how to create extension methods on strings, interfaces, classes such as IQueryable and IEnumerable, and so on. You will write them from scratch and then use them practically in your application. You will also learn the most suitable scenarios for using these extension methods.You will learn everything you need to know about creating your own extension methods and using them and other external extension methods.
Table of Contents (6 chapters)
close
close

Chaining extension methods (Should know)


Method chaining, the core concept behind building fluent interfaces is to allow for better readability. The key to method chaining is to have the extension return an instance of the caller. In later recipes, most extension methods you use will be chained extension methods. If you have used jQuery before, then you have experienced method chaining. This recipe should give you the basic understanding of how and when to chain a method.

Getting ready

Refer to the UserExtensions.cs and Models/Users.cs files in the ExtensionMethods.Library project for the extension methods and class. These methods are used in the Program.cs file in the ExtensionMethods.Console project.

How to do it...

The following code is an upgrade of the previous SetName method that allows chaining:

/// <summary>
/// This is a chained version of SetNames
/// </summary>
/// <param name="value"></param>
/// <param name="fullName"></param>
public static User SetNamesChained(this User value, string fullName)
{
    //the default delimiter is whitespace if no params are passed.
    string[] names = fullName.Split();
    value.FirstName = names[0];
    value.LastName = names[1];
    return value;
}

The following code shows the use of the extension methods:

User user = new User();
string fullName = user.SetNamesChained("Derron Brown").GetFullName();            

How it works...

Method chaining increases code readability, but makes debugging tricky to accomplish; you cannot put break points at each method call to know the value returned by a particular method or which method threw an exception without examining the stack trace. We can only chain methods that return its instance. As seen in the extension usage snippet, we can call another method directly after the SetNamesChained method was called.

Method chaining is mainly used in fluent APIs, such as querying or in very verbose situations like validating and testing conditions. An example of testing conditions would be in the CuttinEdge.Conditions library:

public void GetData(int? id)
{
    Condition.Requires(id, "id")
        .IsNotNull()       // throws ArgumentNullException on failure
        .IsInRange(1, 999) // ArgumentOutOfRangeException on failure
 .IsNotEqualTo(128);// throws ArgumentException on failure
}

Now, the code is much more readable. In this recipe, we have learned one of the core features used by LINQ and other query mechanisms which we will use in later recipes.

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Instant .NET 4.5 Extension Methods How-to
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon