C# 3.0 Features: Extension Methods

C# 3.0 Features: Extension Methods

· Extension methods allow existing classes to be extended without relying on inheritance or having to change the class’s source code. This means that if you want to add some methods into the existing String class you can do it quite easily. Here’s a couple of rules to consider when deciding on whether or not to use extension methods:

  • Extension methods cannot be used to override existing methods
  • An extension method with the same name and signature as an instance method will not be called
  • The concept of extension methods cannot be applied to fields, properties or events
  • Use extension methods sparingly….overuse can be a bad thing!

Here’s an example of creating an extension method in C# that adds a RemoveNonNumeric() method to the String class. Notice that the class is defined as static as well as the extension method itself. The "this" keyword in the parameter signature tells the compiler to add the extension method to the String class since "string" follows the keyword.

namespace StringExtensions

{

public static class StringExtensionsClass

{

public static string RemoveNonNumeric(this string s)

{

MatchCollection col = Regex.Matches(s, "[0-9]");

StringBuilder sb = new StringBuilder();

foreach (Match m in col)

sb.Append(m.Value);

return sb.ToString();

}

}

Here’s an example of how the extension method can be used. You’ll see that the namespace for the extension method class is imported. From there, the compiler treats the RemoveNonNumeric() method as if it was originally part of the standard System.String class.

using StringExtensions;

….

string phone = "123-123-1234";

string newPhone = phone.RemoveNonNumeric();

Update: Although the overall point of the post was to simply show how to create extension methods, Andrex posted a more efficient way to remove non-numeric characters for those that may actually need that specific functionality (I’ll admit I was just throwing something out there :-)). Thanks for commenting Andrex!

public static string RemoveNonNumeric(this string s)

{

StringBuilder sb = new StringBuilder();

for (int i = 0; i < s.Length; i++)

if (Char.IsNumber(s[i]))

sb.Append(s[i]);

return sb.ToString();

}

Update 2: Richard posted the following method which is potentially even faster according to his tests. We’re kind of pulling hairs here, but it’s useful for "anyone who agonizes over every wasted millisecond" as he mentions in the comments (I’m not one of those people :-)). I’m thinking I should start a "How would you refactor this code" series. Could be kind of fun. 🙂

public static string RemoveNonNumeric(this string s)

{

if (!string.IsNullOrEmpty(s))

{

char[] result = new char[s.Length];

int resultIndex = 0;

foreach (char c in s)

{

if (char.IsNumber(c))

result[resultIndex++] = c;

}

if (0 == resultIndex)

s = string.Empty;

else if (result.Length != resultIndex)

s = new string(result, 0, resultIndex);

}

return s;

}

Reference

http://weblogs.asp.net/dwahlin/archive/2008/01/25/c-3-0-features-extension-methods.aspx

C# KeyValuePair Hints

C# KeyValuePair Hints

You need to store two values together in a single collection with the C# programming language. The KeyValuePair struct in System.Collections.Generic is ideal for this purpose, as it is simple and always available. Here we see ways you can use the KeyValueCollection struct in Lists, in methods, and in some algorithms.

Example

First, this example shows how you can use KeyValuePair in a List, which is also in System.Collections.Generic. This is useful for storing pairs of values in a single List. Alternatively, you could use two separate Lists, but that can complicate matters.

Program that uses KeyValuePair [C#]
using System;
using System.Collections.Generic;
class Program
{
 static void Main()
 {
 // Shows a List of KeyValuePairs.
 var list = new List<KeyValuePair<string, int>>();
 list.Add(new KeyValuePair<string, int>("Cat", 1));
 list.Add(new KeyValuePair<string, int>("Dog", 2));
 list.Add(new KeyValuePair<string, int>("Rabbit", 4));
 foreach (var element in list)
 {
 Console.WriteLine(element);
 }
 }
}
Output
[Cat, 1]
[Dog, 2]
[Rabbit, 4]

Overview. This code example shows how you can initialize a new List of type KeyValuePair. Inside the brackets in the KeyValuePair, there are two types separated by a comma. This examples shows KeyValuePairs of one string and one int each.

How to create new KeyValuePairs. Here we see that you can create a new KeyValuePair with its constructor. The constructor is shown in the List.Add calls. The KeyValuePair’s constructor returns the new KeyValuePair, and that instance is added.

Note on arrays. Instead of a List, you could use an array here. You can simply specify the KeyValuePair<string, int> as the type of the array. This would improve performance in many situations.

Return two values

Often, you need to return two separate values from a method. You can do this very easily with KeyValuePair. You must specify the exact type in the return value, and then return the new KeyValuePair in the method body. This is clearer than a two-element array. Consider out or ref parameters instead.

Program that returns two values [C#]
using System;
using System.Collections.Generic;
class Program
{
 static void Main()
 {
 Console.WriteLine(GetNames());
 }
 static KeyValuePair<string, string> GetNames()
 {
 // Gets collection of first and last name.
 string firstName = "William";
 string lastName = "Gates";
 return new KeyValuePair<string, string>(firstName, lastName);
 }
}
Output
[William, Gates]

Read-only compilation error

When using KeyValuePair in your program, you will likely get this error at some point. The C# compiler doesn’t allow you to assign the Key and Value properties. This must be assigned in the constructor.

Property or indexer ‘System.Collections.Generic.KeyValuePair<int,int>.Key’ cannot be assigned to—it is read only

Loop over Dictionary

Probably the most popular usage of KeyValuePair is in a loop over a Dictionary. The Dictionary collection in C# has an enumerator that returns each key and value in a KeyValuePair, one at a time. Examples are available.

Dictionary Examples

Using KeyValuePair with var. An improved syntax could be to use the var keyword with the foreach loop over your Dictionary. This replaces the lengthy KeyValuePair type declaration with three letters.

Foreach Loop Examples

Sort

How can you sort a collection of KeyValuePair instances? You can implement a custom sorting Comparison method. The linked tutorial contains information on this approach.

Sort KeyValuePair List

Shuffle array

As shown in the first example, you may use KeyValuePair in a List to create two parallel Lists. These are very easily sorted, keeping both values together. This site has an example of an accurate shuffle algorithm with KeyValuePair and List.

Shuffle Array

Implementation

You should know what the basic layout of the KeyValuePair struct is. Here, we see the internal code. The KeyValuePair has two private fields, and two public properties that retrieve the values of those fields. The constructor is also shown.

Implementation of KeyValuePair [C#]
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct KeyValuePair<TKey, TValue>
{
 private TKey key;
 private TValue value;
 public KeyValuePair(TKey key, TValue value);
 public TKey Key { get; }
 public TValue Value { get; }
 public override string ToString();
}

ToString method

The ToString method is very useful in KeyValuePair. When you want to display the values, simply call ToString() or pass the KeyValuePair to Console.Write or Console.WriteLine. This will implicitly call ToString(). Internally, ToString() uses a StringBuilder.

Should I use KeyValuePair?

Sometimes. In many cases, such as with internal method code, using KeyValuePair is very convenient and simple. However, using a class or struct you define yourself can definitely enhance the object-orientation of your program. I suggest you prefer classes when the usage is non-trivial.

Summary

In this article, we saw examples of using KeyValuePair in the C# language, and also looked into its internals in the .NET Framework. Lists and Dictionaries are ideal companions for KeyValuePairs. We also saw how you can return the collection from methods.

Collections

Reference:

http://www.dotnetperls.com/keyvaluepair

C#/Windows: Find which account a service is set to “Log On As”

Find which account a service is set to “Log On As”

Problem:

How to find out the user account (Local System/User etc) a service is set to run under ("Log On As")?

Unlike this similar question this code can’t run from within the service itself and the service may not be running.

The System.ServiceProcess.ServiceController class has useful methods for getting the status but not the "Log On As" user.

Solution:

This is the only way I know of, I found it looking around and tested it, it works. Make sure you use the Service Name not it’s Display Name, you will also need to add a reference to System.Management.

private static void GetLogOnAsForAService()

{

string serviceName = "myAppserverService";

SelectQuery query = new System.Management.SelectQuery(string.Format(

"select name, startname from Win32_Service where name = ‘{0}’", serviceName));

using (ManagementObjectSearcher searcher =

new System.Management.ManagementObjectSearcher(query))

{

foreach (ManagementObject service in searcher.Get())

{

Console.WriteLine(string.Format(

"Name: {0} – Logon : {1} ", service["Name"], service["startname"]));

}

}

}

References:

http://stackoverflow.com/questions/1631926/find-which-account-a-service-is-set-to-log-on-as

Error: VS2010 “Find in files” says : “No files were found to look in.Find was stopped”

"Find in files" says : "No files were found to look in.Find was stopped"

Problem:

On some occasions, "Find in files" will just dump this message: "No files were found to look in.Find was stopped", and will not even try searching. This same thing happens often in VS2003. Interesting enough, the first FindInFiles I started after I installed VS2005beta1, it immediatelly happened.

Solution:

The workaround for that, in VS2003, is, when it happens, to press Ctrl+Break (I usually press it a few times, just to be sure, because you don’t see any feedback) and then try again. It always helps. Strange enough, that _same_ workaround does work in VS2005 as well!

References:

http://connect.microsoft.com/VisualStudio/feedback/details/105511/find-in-files-says-no-files-were-found-to-look-in-find-was-stopped

Simplest way to run three methods in parallel in C#

Simplest way to run three methods in parallel in C#

Problem:

I have three methods that I call to do some number crunching that are as follows

results.LeftFront.CalcAi();

results.RightFront.CalcAi();

results.RearSuspension.CalcAi(geom, vehDef.Geometry.LTa.TaStiffness, vehDef.Geometry.RTa.TaStiffness);

Each of the functions is independent of each other and can be computed in parallel with no dead locks.

What is the easiest way to compute these in parallel without the containing method finishing until all three are done?

Solution 1:

See the TPL documentation. They list this sample:

Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork());

So in your case this should just work:

Parallel.Invoke(

() => results.LeftFront.CalcAi(),

() => results.RightFront.CalcAi(),

() => results.RearSuspension.CalcAi(geom,

vehDef.Geometry.LTa.TaStiffness,

vehDef.Geometry.RTa.TaStiffness));

EDIT: The call returns after all actions have finished executing. Invoke() is does not guarantee that they will indeed run in parallel, nor does it guarantee the order in which the actions execute.

Solution 2:

you can do this with tasks too (nicer if you later need Cancellation or something like results)

var task1 = Task.Factory.StartNew(() => results.LeftFront.CalcAi());

var task2 = Task.Factory.StartNew(() => results.RightFront.CalcAi());

var task3 = Task.Factory.StartNew(() =>results.RearSuspension.CalcAi(geom,

vehDef.Geometry.LTa.TaStiffness,

vehDef.Geometry.RTa.TaStiffness));

Task.WaitAll(new []{taks1, task2, task3});

Documentaion:

In .net 4, Microsoft introduced the Task Parrallel library which was designed to handel this kind of problem, see: http://msdn.microsoft.com/en-us/library/dd460693.aspx

References:

http://stackoverflow.com/questions/7320491/simplest-way-to-run-three-methods-in-parallel-in-c-sharp

C#: Running a job in parallel with N concurrent threads

Running a job in parallel with N concurrent threads

Problem:

Sometimes I need a test method to be executed simultaneously by N threads (like what happens in ASP.NET code).

Is there an easy way to do that with Task Library ?

[TestMethod()]

public void DoSomethingTest()

{

// Do something which has concurrency issues i.e. database, IO, …

DoSomething();

}

// Something like:

[TestMethod()]

public void DoSomethingTest()

{

int n = 1000; // run 1000 of DoSomething() simultaneously

Parallel.Invoke(() => DoSomething(), n);

}

Solution:

Yes, there is a Parallel.For :

[TestMethod()]

public void DoSomethingTest()

{

int n = 10; // changed to 10, see comment

Parallel.For(0, n, i => DoSomething());

// here all threads are completed

}

But note that the TPL will decide the amount of parallelism, much like the ASP.NET Threadpool…

You can add ParallelOptions to set the degeree of parallelism but I wouldn’t.

References:

http://stackoverflow.com/questions/5802257/running-a-job-in-parallel-with-n-concurrent-threads