Extension methods in C#

Introduction

Extension methods in C# allow you to extend the functionality of types that you didn’t write and don’t have direct access to. They look like integral parts of any built-in classes in .NET, e.g.:

DateTime.Now.ToMyCustomDate();
string.ToThreeLetterAbbreviation();

You can extend the following types in C#:

  • Classes
  • Structs
  • Interfaces

You can extend public types of 3rd party libraries. You can also extend generic types, such as List of T and IEnumerable of T. You cannot extend sealed classes.

Read more of this post

Join custom objects into a concatenated string in .NET C#

Say you have the following Customer object with an overridden ToString method:

public class Customer
{
	public int Id { get; set; }
	public string Name { get; set; }
	public string City { get; set; }

	public override string ToString()
	{
		return string.Format("Id: {0}, name: {1}, city: {2}", Id, Name, City);
	}
}

Read more of this post

How to create custom string formatters with C# .NET

.NET has a fairly large number of built-in string formatters that you can pass into the string.Format method. Here are some examples from the MSDN page about formatting:

String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
                                city.Item1, city.Item2, city.Item3, city.Item4, city.Item5,
                                (city.Item5 - city.Item3)/ (double)city.Item3);
String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}\n",
                                    "City", "Year", "Population", "Change (%)");
String.Format("{0,-10:C}", 126347.89m);         

The IFormatProvider and ICustomFormatter interfaces will provide you with the methods required to create your own formats.

Read more of this post

Using NumberStyles to parse numbers in C# .NET

There are a lot of number formats out there depending on the industry we’re looking at. E.g. negative numbers can be represented in several different ways:

  • -14
  • (14)
  • 14-
  • 14.00-
  • (14,00)

…and so on. Accounting, finance and other, highly “numeric” fields will have their own standards to represent numbers. Your application may need to parse all these strings and convert them into proper numeric values. The static Parse method of the numeric classes, like int, double, decimal all accept a NumberStyles enumeration. This enumeration is located in the System.Globalization namespace.

Read more of this post

5 ways to compress/uncompress files in .NET

There are numerous compression algorithm out there for file compression. Here come 5 examples with how-to-do links from this blog.

Compressing individual files

The following algorithms can be used to compress a single file. E.g. source.txt will be compressed to source.txt.gz.

Read more of this post

Calculate standard deviation of integers with C# .NET

Here comes a simple extension method to calculate the standard deviation of a list of integers:

public static double GetStandardDeviation(this IEnumerable<int> values)
{
	double standardDeviation = 0;
	int[] enumerable = values as int[] ?? values.ToArray();
	int count = enumerable.Count();
	if (count > 1)
	{
		double avg = enumerable.Average();
		double sum = enumerable.Sum(d => (d - avg) * (d - avg));
		standardDeviation = Math.Sqrt(sum / count);
	}
	return standardDeviation;
}

Here’s how you can call this method:

List<int> ints = new List<int>() { 4, 7, 3, 9, 13, 90, 5, 25, 13, 65, 34, 76, 54, 12, 51, 23, 3, 1, 7 };
double stdev = ints.GetStandardDeviation();

View all various C# language feature related posts here.

How to build URIs with the UriBuilder class in C#

You can normally use the URI object to construct URIs in C#. However, there’s an object called UriBuilder which lets you build up a URI from various elements.

Here’s an example to construct a simple HTTP address with a scheme, a host and a path:

UriBuilder uriBuilder = new UriBuilder();
uriBuilder.Scheme = "http";
uriBuilder.Host = "cnn.com";
uriBuilder.Path = "americas";
Uri uri = uriBuilder.Uri;

uri will be “http://cnn.com/americas&#8221;.

Read more of this post

Combinable enumerations in C# .NET

You’ve probably encountered cases with combined enum values using the pipe character, i.e. the “bitwise or” operator ‘|’:

Size.Large | Size.ExtraLarge

Let’s see an example of how to create such an enum.

The enumeration is decorated with the Flags attribute like in the following example:

Read more of this post

How to pass any number of parameters into a method in C# .NET

You must have come across built-in methods in .NET where you can send any number of arguments into a method. E.g. string.Format has an overload where you can pass in a format string and then an array with the “params” modifier.

There’s nothing stopping you from using the same keyword to write a similar method, here’s an example:

public void MethodWithParams(int toBeMultiplied, params int[] multipliers)
{
	foreach (int m in multipliers)
	{ 
		Console.WriteLine(string.Format("{0} x {1} = {2}", toBeMultiplied, m, toBeMultiplied * m));
	}
}

Read more of this post

How to hide the key pressed in a .NET console application

You probably know how to read the key pressed by the user in a .NET console application by the Console.ReadKey() method:

ConsoleKeyInfo pressedKey = Console.ReadKey();
Console.WriteLine("You have pressed: {0}", pressedKey.Key);

Read more of this post

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.