FeedC# TutorialArchiveAbout

Iterator Pattern C#

Iterator Pattern C#

Contents

What Is Iterator Pattern?

The Iterator pattern provides a way of accessing elements of a collection sequentially, without knowing how the collection is structured.

The idea is that an aggregate object such as an array or list will give you a way to access its elements without exposing its internal structure.

Moreover, you might want to traverse the list in different ways, depending on what you want to accomplish. But you probably don’t want to bloat the List interface with operations for different traversals, even if you could anticipate the ones you will need. You might also need to have more than one traversal pending on the same list.

The Iterator pattern lets you do all this. The key idea in this pattern is to take the responsibility for access and traversal out of the list object and put it into an iterator object.

C# String.Format() and StringBuilder

C# String.Format() and StringBuilder

Note: If you are not familiar with String.Format and StringBuilder you can learn about it in my blog post C# String.

Recently, I saw some code that looked something like this:

StringBuilder builder = new StringBuilder();
builder.Append(String.Format("{0} {1}", firstName, lastName));
// Do more with builder...

Now, I don’t wana get into arguments about how String.Concat() is more performant here. String.Format() allows code to be more easily localized and it is being used for that purpose here. The real problem is that StringBuilder.AppendFormat() should be used instead:

StringBuilder builder = new StringBuilder();
builder.AppendFormat("{0} {1}", firstName, lastName);
// Do more with builder...

C# Pattern Programs

This article explains various star (*) pattern programs in c# programming language. You can download the complete project from here containing source code for all the star pattern programs discussed in this article.

Content

Generics In C#

Generics In C#

Generics in C# were introduced into the C# language with version 2 of the C# specification and the goal was to allow us to reuse more code while still being typesafe.

The type parameters in c# generics allow you to create type-safe code without knowing the final type you will be working with. In many instances, you want the types to have certain characteristics, in which case you place constraints on the type. Also, C# methods can have generic type parameters as well whether or not the class itself does.

Generics in C# allows for code reuse, as generics can parameterize the types inside of a class, interface, method or delegate. It also helps to avoid nasty problems, like typecasting and boxing.

Contents