Professional Documents
Culture Documents
C#
Anoop Madhusudanan :
http://amazedsaint.com
This book is intended to be a value adding reading material
for beginner to intermediate C# programmers. It may also
be used for accelerating the learning about new and
upcoming features in C#, and also to get an introduction
about new libraries in .NET. You may find random articles
and alternate perspectives related to various aspects of C# -
ranging from delegates, lambdas, fluent interfaces, dynamic
features etc. with practical examples.
Revisiting C# 1
Contents
Contents ........................................................................................................................................................ 1
Revisiting Delegates, Anonymous Methods and Lambdas ........................................................................... 2
Creating Fluent Interfaces In C#.................................................................................................................... 6
Anonymous Types in C# and Object Initializer Syntax ................................................................................ 10
Type Inference in Generic Methods ........................................................................................................... 12
The Case Of switch-case in C#..................................................................................................................... 13
C# 4.0 dynamic Features – Under the hood ............................................................................................... 15
Mr ExpandoObject in C# 4.0 ....................................................................................................................... 23
C# Enums – A Second Look ......................................................................................................................... 25
Top 5 Developer Mistakes C# Developers Should Not Commit.................................................................. 27
4 .NET 4.0 Libraries You Should Know About ............................................................................................. 31
Further Reading .......................................................................................................................................... 32
Revisiting C# 2
Delegates
We know that a delegate is a type that can reference a method. For example, consider this example to
define a delegate and create a delegate instance.
The above code will give you an output of 50, no doubt, right ? :)
Anonymous Methods
Now, you may know that with C# 2.0, we can use anonymous methods to create a delegate instance
without a named method. Let us re-write the above implementation leveraging an anon method.
Instead of the method name, you‟ve to use the „delegate‟ keyword. Also, note that there is no need to
specify a return type – because the return type will be inferred from the delegate signature.
Lambdas
And of course, you might also know that with C# 3.0, you can use Lambdas for producing anonymous
methods. A lamda expression is exactly a function, that can contain statements and expressions. Here
is the equivalent of above code, still shortened using a lambda
1.
2. //Example 3 - Creating a delegate instance using statement lambda
3.
4. public delegate int BinaryOperationDelegate(int x, int y);
5. class Program
6. {
7. static void Main(string[] args)
8. {
9. //Create a delegate instance using a statement lambda
10. BinaryOperationDelegate add =(a,b)=>{
11. //this statement block can contain
12. //multiple statements
13. return a+b;
14. };
15.
16. int result = add(20, 30);
17. Console.WriteLine(result);
18. }
19.
20.
21. }
In the above example, note the lambda syntax that replaces the anon method syntax in example 2
1. (a,b)=>{
2. return a+b;
3. };
The types of input parameters a and b and the return type will be inferred correctly by the compiler,
based on the context. How ever, on scenarios where the compiler can't infer the type directly, you can
provide that explicitly. Like this.
BinaryOperationDelegate add =(int a, int b)=>{ return a+b; };
There are basically two type of lambdas - Statement Lamdas and Expression Lambdas. The above
example shows a statement lambda, as the right hand expression is inside a statement block, of the
form
If you won't have input parameters, you may use the syntax
Revisiting C# 4
=> simply means 'goes to', and you may say that the input parameters goes to the statements (for
some processing) :)
We‟ve seen how to create Statement lambdas in the above example. Now, let us explore a bit about
Expression Lambdas (or single line lambdas). The syntax is similar to statement lambdas, but for
expression lambdas, the right hand expression shouldnot be inside a statement block { }. Instead of
having statements on the right side, an Expression Lambda can have a single line expression on the
right hand side. Here is the simple example, with out the statement block.
The above code produces the same result as in the case of stament lambdas. How ever, Expression
lamdba has an advantage over statement lambda. When an expression lambda is assigned to a
variable of type Expression, the compiler emits code to build an expression tree that represents the
lambda expression, instead of a delegate instance.
In the above example, you saw that we are assigning our expression lambda to the
System.Linq.Expression<TDelegate> to create an expression tree, and the compiling it to get the
actual delegate. Expression trees provide us a powerful way to represent code/logic as data, that can
be modified and/or interpreted at runtime if required.
1. animals.ForEach(animal=>Console.WriteLine(animal.Name));
This is a post about creating Fluent interfaces in C#, just to demonstrate various possibilities of Fluent
programming.
Assuming that you are interested in training animals, let us start with a simple ITrainable interface. :)
1.
2. /// <summary>
3. /// Anything that is trainable
4. /// </summary>
5. public interface ITrainable
6. {
7. ITrainable Train(string skill);
8. ITrainable Do(string skill);
9. }
Well, nothing fancy there. Let us go ahead and create a Dog Class, which implements this interface.
The only interesting piece you may find in the Dog class is, all methods are returning a type of
ITrainable. As long as our Dog class implements ITrainable, we can return 'this', i.e the current Dog
Instance.
1. /// <summary>
2. /// Our simple dog class
3. /// </summary>
4. public class Dog : ITrainable
5. {
6. public string Name { get; set; }
7. public List<string> Skills { get; set; }
8.
9. public Dog(string name)
10. {
11. Console.WriteLine();
12. Console.WriteLine("Dog " + name +
13. " created");
14.
15. Name = name;
16. Skills = new List<string>();
17. }
18.
19. //Let us train this skill to our dog
20. //Note that we are returning 'this', so that
21. //we can continue training or ask the dog to perform
22. public ITrainable Train(string skill)
23. {
24. Console.WriteLine("Dog " + Name +
25. " learned " + skill);
26. this.Skills.Add(skill);
Revisiting C# 7
As you can see, we are chaining the method calls, because in each call, we are returning an object of
type ITrainable. You'll see what Bobby is doing in the console
Now, let us do something more interesting. Let us create a couple of extension methods for all
collections of ITrainable. We do this by writing an extension method for IEnumerable<ITrainable>. If
you see, our extension methods are accepting a bunch of trainable organisms(?) (read,
IEnumerable<ITrainable>) and returns the same.
Leave out the Console.WriteLine(), it is there just for some pretty printing.
1.
2.
3. /// <summary>
4. /// Let us fluently train a bunch of Trainable
5. /// animals
6. /// </summary>
7. public static class TrainableExtensions
Revisiting C# 8
8. {
9. //Note that we are returning the IEnumerable<ITrainable>
10. public static IEnumerable<ITrainable>
11. Train(this IEnumerable<ITrainable> flock, string skill)
12. {
13. foreach (var member in flock)
14. member.Train(skill);
15. Console.WriteLine();
16. return flock;
17. }
18.
19. //Ask all members to perform a skill
20. public static IEnumerable<ITrainable>
21. Do(this IEnumerable<ITrainable> flock, string skill)
22. {
23. foreach (var member in flock)
24. member.Do(skill);
25. Console.WriteLine();
26. return flock;
27. }
28.
29. }
Now, as LINQ methods are essentially extension methods on top of IEnumerable<T>, you can mix
and match the extension methods we just wrote, with LINQ methods. For example, if we decide only
Rob should learn a special skill (JumpingRing), you can do this.
1. dogs.Train("EatingFood").Skip(2)
2. .Train("JumpingRing").Union(dogs)
3. .Train("TakingPaper");
And finally, Fluent APIs can be used for much more useful tasks (If you havn't yet realized, lol). Few
fluent API's I've come across
Rhino Mocks
ReadableRex
Tweet#
Revisiting C# 10
It is well known that starting from C# 3.0, you can initialize an object like this.
You specify the properties of an object, and at compile time, the compiler will create a new
(anonymous) type, with the properties you specify, and with a constructor that can take the same
number of arguments. Now, let us examine our anonymous type in detail by using reflection. We'll
examine whether the type is a class, along with the type's name. If you run this,
Needless to say, the Name will be a random name, and the Assembly's name depends on your own
project name. The key point is, we just established that the type is there in the assembly - which
means, as I mentioned, the compiler created a type at compile time itself. You can have a look at the
IL if you are interested.
Now, let us examine the observation that the anonymous type has a constructor that takes the same
number of arguments as that of properties (i.e, in this case, the number of constructor arguments will
be equal to the number of properties we specified in the object initializer, of types string and int). We
can do that easily by creating a new instance of the anonymous type we have, using reflection. Add
this to the tail end of the last piece of code.
1. //These two calls will fail with a run time exception, Just keep them commented
2. //var newboy = Activator.CreateInstance(boy.GetType(), null);
3. //var newboy = Activator.CreateInstance(boy.GetType(), new object[] { "Joe"});
4.
5. //Only this will work. Creating a new boy
6. var newboy=Activator.CreateInstance(boy.GetType(),new object[]{"Joe",2});
Revisiting C# 11
7.
8. //Just write back the name of new boy
9. Console.WriteLine(newboy.GetType().GetProperty("Name").GetValue(newobj, null));
You can see that only the last call will work, as we need to pass the same number of arguments while
instantiating. Note that you can have arrays of anonymous types as well, like this.
Furthermore, I just want to mention one more point. You may not need to assign the property
explicitly, when you use the object initializer syntax. Consider this code.
The key point to note here is, for guy 2, we are not explicitly specifying the Name property. Instead,
we are just specifying that the name of Guy2 is same as Guy1. The compiler will assume the property
name from the given parameter's name (in fact, the last part of the specified parameter, in this case
'Name') - This is called Projection. Obviously, you'll find that both guy1 and guy2 are of the same type
as well.
Why anonymous types are interesting? Because we use them in various ways, especially while using
LINQ syntax. Here is a basic example
Here, you'll probably find that we are using projection in the select new block. And as the last pointer,
just debug and observe the type of oldGuys, and have a look at the base's type.
Revisiting C# 12
1. class Program
2. {
3. //Our generic IsGreaterThan method
4. public static bool IsGreaterThan<T>(T x, T y) where T : IComparable<T>
5. {
6. return (x.CompareTo(y) > 0);
7. }
8.
9. static void Main(string[] args)
10. {
11. //You don't need to explicitly specify IsGreaterThan<int>
12. var result = IsGreaterThan(20,10);
13. Console.WriteLine(result);
14. }
15.
16. }
As you can see, we are not specifying the type explicitly, while calling our IsGreaterThan method - it is
inferred automatically by the compiler. That is simple, isn‟t it? Now, things become a a bit more
interesting when you combine Generic method type inference with extension methods. Have a look at
this code, we just made our IsGreaterThan<T> method an extension method.
As you can see, we are still good - the compiler can still infer the types. And of course, you can
leverage our IsGreaterThan against any IComparable implementation.
Revisiting C# 13
1. switch (foo) {
2. case 'case1':
3. alert('case1 code');
4. break;
5. case 'case2':
6. alert('case2 code');
7. break;
8. default:
9. alert('hm, default code');
10. break;
11. }
a number of developers may consider the below one as more elegant - because it is re-usable and
more testable.
1. var mySwitch= {
2. 'case1' : function() {
3. alert('case1 code');
4. },
5. 'case2' : function() {
6. alert('case2 code');
7. },
8. 'default' : function() {
9. alert('default code');
10. }
11. };
12.
13.
14. if (mySwitch[foo]) {
15. mySwitch[foo]();
16. } else {
17. mySwitch['default']();
18. }
I was thinking about implementing something along similiar lines in C#, to re-factor few fat switch
cases using a Dictionary. Obviously, this is context specific - one approach won't fit all the scenarios.
Here is a quick example to clarify the point.
12.
13. //Now, somewhere else
14.
15. var mySwitch = new SwitchCase
16. {
17. { "case1", ()=>Console.WriteLine("Case1 is executed") },
18. { "case2", ()=>Console.WriteLine("Case2 is executed") },
19. { "case3", ()=>Console.WriteLine("Case3 is executed") },
20. { "case4", ()=>Console.WriteLine("Case4 is executed") },
21. { "default",()=>Console.WriteLine("Default is executed") },
22. };
23.
24. mySwitch.Eval(c);
This provides loose coupling, and you can even modify the logic for each case easily using a setter or
so.
Revisiting C# 15
Let us start with a bare minimum program. Fire up VS2010 and try the following code.
It is obvious that this won‟t compile. Simply because, the compile/design time checking ensures type
safety - and as we don‟t have a method named SomeStupidCall in our Human class, we can‟t compile
the same.
Now, let us take a step back, and modify the above code like this. Change the type of variable h to
„dynamic‟. And Compile. Here is a little surprise!! You got it compiled!! By using „dynamic‟ keyword,
you just told the compiler, “dude, don’t bother if SomeStupidCall() is there in the Human type”
And now, run the application. The application will break for sure. But hey, that is your fault, not the
compiler‟s.
I hope the above scenario is „good‟ enough to give you an „evil‟ impression about the dynamic
features. But, wait. There are lot of scenarios where the dynamic features can really simplify things for
you. For example, let us assume a reflection based scenario, where you load a type (from an external
assembly or so), to invoke a member. Here is a quick example. You‟ll see how to use dynamic as an
easier alternative for reflection. This is much more evident when you deal with scenarios like COM
interop etc. We‟ll see more interesting uses later.
Revisiting C# 18
Let us get back to a basic example. Consider a human class, with a Walk() method and Age property.
Now, let us create a new Human and assign this to a dynamic variable „h‟.
Revisiting C# 19
Let us build the above application. Fire up Reflector, open the binary executable of the app, and have
a look at the same. With a bit of cleanup, this is the relevant part of the disassembled code - which is
the equivalent 'statically‟ typed code generated by the compiler, for the „dynamic‟ code we wrote
above.
You‟ll see a „SiteContainer‟, for keeping track of the context, and two call site fields.
And here is the disassembled code for the member invocations. It might be interesting to note that,
the variable „h‟ is compiled as a simple CLR „object‟. Wow, from the CLR point of few, there is nothing
like a „dynamic‟ type. Instead, all member invocations to our „dynamic‟ object are modified; in such a
way that they are piped through a dynamic Call Site. The Call Site is initialized with the Binder
responsible for run time binding. In this case, you may note that the C# run time binder will be used
to invoke the members(Microsoft.CSharp.RuntimeBinder.Binder „s InvokeMember will return a CallSite
binder, that‟ll be used by the Call Site).
Revisiting C# 20
You might be thinking how the code will be generated for scenarios where, you have a method that
accepts or returns a „dynamic‟ type, or a property that gets or sets a dynamic type. Let us try this out.
Change our above Human class in the above example, to something like this. Note that now Walk
method accepts a dynamic type, and Age property is also modified to get/set dynamic types.
Revisiting C# 21
Have a sneak peak using Reflector. You‟ll note that, the compiler has generated a special [Dynamic]
attribute to the input parameter of Walk() method. Also, the getter and setter of the Age property is
also decorated with the [Dynamic] attribute, as shown below.
Conclusion
And here is some code of the final form of our experiment. Create a Console app in C# 4.0, to play
with this.
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Runtime.CompilerServices;
6. using Microsoft.CSharp.RuntimeBinder;
7.
8. namespace DynamicTest
9. {
10. class Human
11. {
12. public void Walk(dynamic place)
13. {
14. Console.WriteLine("I'm walking to " + place);
15. }
16. public dynamic Age { get; set; }
17. }
18.
19. class Program
20. {
21. // Methods
22. private static void Main(string[] args)
23. {
Revisiting C# 22
Mr ExpandoObject in C# 4.0
.NET framework 4.0 has a cool new ExpandoObject class, in System.Dynamic namespace. What
makes this special is, it allows you to create an object with members that can be dynamically added
and removed at run time.
And you'll get 10 as output in your console. As you can see, the property 'Value' and method
'WriteNow' is attached at runtime, when the invocation happens.
The objective of this post is to examine how the ExpandoObject itself is implemented. To make this
clear, let us create a MyExpando class, a minimal implementation of ExpandoObject.
We are inheriting MyExpando class from the DynamicObject, and these are the major methods we are
overriding.
And Here is our minimal MyExpando class, inherited from DynamicObject, and overrides the above
methods.
9. /// </summary>
10. public override bool TrySetMember(SetMemberBinder binder, object value)
11. {
12. if (!_members.ContainsKey(binder.Name))
13. _members.Add(binder.Name, value);
14. else
15. _members[binder.Name] = value;
16.
17. return true;
18. }
19.
Revisiting C# 24
Whenever a property set operation happens, the runtime will invoke TrySetMember, and there, we are
pushing the property name and value to a dictionary. Similarly, whenever a get operation happens
(TryGetMember), we are simply returning the value object if available in the dictionary. Also, when a
method call is made (TryInvokeMember), if the value type is a delegate, we just invoke the same by
passing the arguments we received. Pretty simple, huh? Well, that is it. Now, let us try the above
scenario with our MyExpando object
If you already found the issue, you may stop reading here. Otherwise, let us examine this in a bit
detail.
Assume that a caller, let us sayCaller1, is requesting a security key for leveraging admin permissions.
Now, the issue. As you may be aware, C# enums are implemented as integers by default, and you can
cast integers to an enum type. So, if the Caller2 has some evil plans, it may do something like this.
Note that I'm casting an integer to an enum, and the following exclusion check will be bypassed by
Caller2, because the token's value is 10, instead of the value for SecurityToken.Admin.
Alright, so the point is, be a bit more careful when working with Enums in general, and also when you
implement check conditions with enums.
Now, there is a better solution - An explicit check using Enum.IsDefined(..) to validate if the passed
value exists in the specified enumeration is the best solution.
Revisiting C# 27
This a pretty „old thing‟ - but surprisingly, still a very common mistake.
As TheSoftwareJedi mentioned, you don‟t really need to break the stack while throwing exceptions.
I‟ve done this myself when I was a beginner - and I‟ve seen this more often than anything else when I
do code reviews these days.
and
try {..} catch(Exception ex) { throw; } ?
And when you lose the stack trace, you can‟t debug your app – and even worse, you can‟t log your
error details properly to your error log.
Do not rethrow by throwing the same exception object. This causes the stack trace for the original
exception to be lost--use a lone "throw;" statement (without an object following it) to "rethrow" a
catch exception.
As a rule, when you use an IDisposable object, you should declare and instantiate it in a using
statement. The using statement calls the Dispose method on the object in the correct way, and it
also causes the object itself to go out of scope as soon asDispose is called. Within the usingblock, the
object is read-only and cannot be modified or reassigned.
The using statement ensures that Dispose is called even if an exception occurs while you are calling
methods on the object. You can achieve the same result by putting the object inside a try block and
then calling Dispose in a finally block; in fact, this is how the using statement is translated by the
compiler.
Also, do you know that a using statement is expanded by the compiler to a try{..} finally{..} block at
compile time? Read more tips about using statement in MSDN.
I think Scott Langham brought up a great point about not unhooking event handlers. People don‟t
really „remember‟ to unhook events.
Revisiting C# 29
In C#, when you register an event handler, you are creating a strong reference from the event source
to the listener. So, the listener won‟t get garbage collected even if you don‟t have any pointers to the
listener - unless you unhook the event by yourself, and this might even result in a memory leak.
So, if you are thinking about how to deal with situations where your Source is having a longer life
span than the listener – there are multiple ways to deal with it, and Daniel Grunwald covers them
nicely in this excellent Codeproject Post.
In .NET, we know that strings are immutable – which means, once a string is created, its value can‟t
be changed. All string operations you perform, actually returns a new string containing the
modification.
John Sonmez have a nice point with an example.
Why this is important? If Hashcode of two items does not match, they‟ll be never considered equal,
and the Equals method will never be called to execute your custom comparison logic – let us say, in
scenarios where your objects are used as a key in a dictionary or so. Hence, in first place, you should
Revisiting C# 30
override GetHashCode and return the same value for two equal objects based on comparison logic.
I‟ve seen this a couple of times during code review.
So, though Mark Gravell has several interesting points in his answer, my pick is about not overriding
GetHashCode when you override Equals method in C#.
Revisiting C# 31
Further Reading
Also, check out my EBook on Design patterns here
On the C# side, here are few more interesting reads for you.