Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Saturday, 3 July 2010

Get Method Names using Reflection [C#]

If you want to get method names of a given type in C#, you can use method Type.GetMethods. This method returns array of MethodInfo objects. MethodInfo contains many informations about the method and of course a method name (MethodInfo.Name). To filter returned methods (for example if you want to get only public static methods) use BindingFlags parameter when calling GetMethods method. Required are at least two flags, one from Public/NonPublic and one of Instance/Static flags. Of course you can use all four flags and also DeclaredOnly and FlattenHierarchy. BindingFlags enumeration and MethodInfo class are declared in System.Reflection namespace.

This example gets names of public static methods of MyClass, sorts them by name and writes them to console.
[C#]

using System.Reflection;

// get all public static methods of MyClass type
MethodInfo[] methodInfos = typeof(MyClass).GetMethods(BindingFlags.Public |
BindingFlags.Static);
// sort methods by name
Array.Sort(methodInfos,
delegate(MethodInfo methodInfo1, MethodInfo methodInfo2)
{ return methodInfo1.Name.CompareTo(methodInfo2.Name); });

// write method names
foreach (MethodInfo methodInfo in methodInfos)
{
Console.WriteLine(methodInfo.Name);
}

Stupid C# tricks: Working with indexers

One of C#'s most interesting features is the class indexer. Simply put, an indexer is a special kind of property that allows you to reference your class like you would an array. Obviously, this ability becomes useful when creating a collection class, but giving a class array-like behavior can be useful in other situations, such as when dealing with a large file or abstracting a set of finite resources. In this article, I'll show you how to set up a class to use an indexer. But first, let's get some necessary background by reviewing the concept of properties.

Properties 101

If you've done any programming in VB6, you'll be familiar with property methods—special class members that allow controlled access to a private class field. In C#, you have two kinds of properties: get, which allows you to return the value of a private field, and set, which allows you to set the value of a private field. As a simple example, consider the code below, which creates a FirstName property to control access to the private class member firstname:

class Person {
private string firstname;
public string FirstName {
get {return firstname;}
set {firstname = value;}
}
}

That property declaration would allow you to write code like this:
Person p = new Person();
p.FirstName = "Lamont";
Console.WriteLine (p.FirstName);

As you can see, a property declaration looks a lot like a field declaration, except that it's declared with two special members, called accessors in Microsoft parlance. The get accessor is called when the property is invoked on the right-hand side of an expression or used as a parameter to another routine. The set accessor is called when the property is invoked on the left-hand side of an expression and sets the value of its associated private field via the implicitly passed value parameter. You'd create a read-only property by omitting the set accessor, which would cause any attempts to set the property to generate compiler errors.

Using indexers for fun and profit
So why did I launch myself on that tangent? Because a class indexer works almost exactly like a property and looks very similar when you examine the code. Here's a sample class with an indexer that returns a string:

class Sample {
public string this [int index] {
get {return "You passed " + index; }
)
}

Notice that the property name is this, which refers back to the current instance of the class, and that the parameter list is enclosed in square brackets instead of parentheses. Also, this is a read-only indexer. To make it read/write, I'd have to add a set accessor. When defining an indexer, you are not limited to a single parameter. Indexer parameters may be of any type, although int usually makes the most sense. It's also possible to have more than one indexer in the same class (overloading)—more on that later.

Having defined Sample in this way, we can use the indexer as a sort of default property, like so:
Sample s = new Sample();
Console.WriteLine(s[55]);

Properties vs. indexers

There are a few differences between properties and indexers. Essentially, they boil down to the following:

* Each property in a class must have a unique name, while each indexer defined in a class must have a unique signature or parameter list. (This allows indexer overloading.)
* Properties can be static, while indexers must always be instance members.
* Accessors defined for an indexer can access parameters passed to the indexer, while property accessors have no parameters.


Advanced tricks: Interfaces

When array-like behavior is desired for an implementer, you can define indexers for interfaces. In fact, the IList and IDictionary collection interfaces both declare an indexer to provide access to the items they're storing.

When declaring an indexer for an interface, remember that the declaration just serves to indicate the existence of the indexer. You need only provide the appropriate accessors and should not include a scope modifier. The following is an example of an indexer declared as part of an interface appropriately named

IImplementMe:
interface IImplementMe {
string this[int index]
{
get;
set;
}


An implementing class would have to provide the implementations for both the get and set accessors for IImplementMe's indexer.

That'll about do it for now. You should have a strong enough understanding of indexers to play with them on your own. Have fun.

Anonymous Methods vs Threads

With the release of .NET Framework 2.0, we have gained access to a very powerful feature called Anonymous Methods. I'm sure that almost any .NET developer has used Anonymous Method at least once and most of us use them on a daily basis.

Typically you use Anonymous Methods when you want to declare an event handler inline, without the need of creating a separate, named method (hence the name Anonymous). Other usage areas include delegates of types such As Predicate or Action. Mentioned delegates are most often used in methods found on all types of collection related classes be it Array or List. Typical code for this may look like this:

string[] urls = GetUrls();

string[] urlWithWww;
urlWithWww = Array.FindAll(urls, delegate(string url)
{
return url.StartsWith("www");
});

Nothing unusual here. The usefulness of Anonymous Methods comes from the fact that they allow us to access variables defined in the scope in which the very method is defined. Here as an example of how this feature is usually used:

string pattern = ".com";

string[] urls = GetUrls();
string[] urlWithWww;
urlWithWww = Array.FindAll(urls, delegate(string url)
{
return url.Contains(pattern);
});

Great feature indeed, but there is one gotcha that we have to be aware. The problem most often appears when we start to work with multiple threads. Given the following code:

foreach (string url in urls)

{
DoSomethingAsync(delegate()
{
Debug.WriteLine(url);
});
}

We have to know that the url variable that we pass to a Debug.WriteLine method is "shared" among all Anonymous Methods and because of this, we may (and most probably we will) get results that we do not expect: same url printed few times, than a different url, again printed few times. Confusing, isn't it?

Why is that? Brad Adams explains the mechanism behind this strange behavior here (scroll down to the comments). It's worth mentioning that you could get the same strange behavior without working with multiple threads. It is just far more common to get it while theading.

To make things more "predictable", the code above has to be written in a slightly different way:

for (int i = 0; i < style="color: rgb(0, 0, 255);">string url = urls[i];

DoSomething(delegate()
{
Debug.WriteLine(url);
});
}

Now every Anonymous Method gets its own copy of url and everything works as expected.