C# in Depth

Jon Skeet

Mentioned 24

A guide to the key topics of C# covers such topics as lambda expressions, LINQ, generics, nullable types, iterators, and extension methods.

More on Amazon.com

Mentioned in questions and answers.

What is the use of IQueryable in the context of LINQ?

Is it used for developing extension methods or any other purpose?

In essence its job is very similar to IEnumerable<T> - to represent a queryable data source - the difference being that the various LINQ methods (on Queryable) can be more specific, to build the query using Expression trees rather than delegates (which is what Enumerable uses).

The expression trees can be inspected by your chosen LINQ provider and turned into an actual query - although that is a black art in itself.

This is really down to the ElementType, Expression and Provider - but in reality you rarely need to care about this as a user. Only a LINQ implementer needs to know the gory details.

Re comments; I'm not quite sure what you want by way of example, but consider LINQ-to-SQL; the central object here is a DataContext, which represents our database-wrapper. This typically has a property per table (for example, Customers), and a table implements IQueryable<Customer>. But we don't use that much directly; consider:

using(var ctx = new MyDataContext()) {
    var qry = from cust in ctx.Customers
              where cust.Region == "North"
              select new { cust.Id, cust.Name };
    foreach(var row in qry) {
        Console.WriteLine("{0}: {1}", row.Id, row.Name);

this becomes (by the C# compiler):

var qry = ctx.Customers.Where(cust => cust.Region == "North")
                .Select(cust => new { cust.Id, cust.Name });

which is again interpreted (by the C# compiler) as:

var qry = Queryable.Select(
                  cust => cust.Region == "North"),
              cust => new { cust.Id, cust.Name });

Importantly, the static methods on Queryable take expression trees, which - rather than regular IL, get compiled to an object model. For example - just looking at the "Where", this gives us something comparable to:

var cust = Expression.Parameter(typeof(Customer), "cust");
var lambda = Expression.Lambda<Func<Customer,bool>>(
                      Expression.Property(cust, "Region"),
                  ), cust);

... Queryable.Where(ctx.Customers, lambda) ...

Didn't the compiler do a lot for us? This object model can be torn apart, inspected for what it means, and put back together again by the TSQL generator - giving something like:

 SELECT c.Id, c.Name
 FROM [dbo].[Customer] c
 WHERE c.Region = 'North'

(the string might end up as a parameter; I can't remember)

None of this would be possible if we had just used a delegate. And this is the point of Queryable / IQueryable<T>: it provides the entry-point for using expression trees.

All this is very complex, so it is a good job that the compiler makes it nice and easy for us.

For more information, look at "C# in Depth" or "LINQ in Action", both of which provide coverage of these topics.

In C# in depth (an excellent book thus far), Skeet explains events aren't fields. I read this section many times and I don't understand why the distinction makes any difference.

I am one of those developers that confuse events and delegate instances. In my mind, they are the same. Aren't both just a form of indirection? We can multicast both. An event is setup as a field as shorthand...sure. But, we are adding or removing handlers. Stacking them up to be called when the event fires. Don't we do the same thing with delegates, stack them up and call invoke?

The other answers are basically correct, but here's another way to look at it:

I am one of those developers that confuse events and delegate instances. In my mind, they are the same.

An old saying about not seeing the forest for the trees comes to mind. The distinction that I make is that events are at a higher "semantic level" than a field of delegate instance. An event tells the consumer of the type "hi there, I am a type that likes to tell you when something happens". The type sources an event; that's part of its public contract.

How, as an implementation detail, that class chooses to keep track of who is interested in listening to that event, and what and when to tell the subscribers that the event is happening, is the business of the class. It happens to typically do so with a multicast delegate, but that's an implementation detail. It is such a common implementation detail that it is reasonable to confuse the two, but we really do have two different things: a public surface, and a private implementation detail.

Similarly, properties describe the semantics of an object: a customer has a name, so a Customer class has a Name property. You might say that "their name" is a property of a customer, but you would never say that "their name" is a field of a customer; that's an implementation detail of a particular class, not a fact about the business semantics. That a property is typically implemented as a field is a private detail of the class mechanics.

I am using the below code

var processed = new List<Guid>();
Parallel.ForEach(items, item => 

Is the above code thread safe? Is there a chance of processed list getting corrupted? Or should i use a lock before adding?

var processed = new List<Guid>();
Parallel.ForEach(items, item => 


To quote from Jon Skeet before he gets here:

As part of Parellel Extensions in .Net 4, there are several new collections in a new System.Collections.Concurrent namespace. These are designed to be safe in the face of concurrent operations from multiple threads, with relatively little locking.

These include IProducerConsumerCollection<T>, BlockingCollection<T>, ConcurrentBag<T>, ConcurrentQueue<T>, ConcurrentStack<T>, and ConcurrentDictionary<TKey, TValue> among others.

As i am a beginner who just finished my engineering and i have good knowledge in c,c++... I thought of studying c# as well but i found that c# 4.0 has been released.....

  • Should i care about the previous versions?
  • What are the tips you give for beginner to learn c# quickly?
  • what are the factors to be considered when moving from c,c++ to c#?

Should i care about the previous versions?

Yes. You should at least know which features of 4.0 the older version DON'T have.

There's a good chance that if you're using .NET on the job, they're not going to be at 4.0 yet. Therefore, you're going to need to know which features you can use and which you're going to have to work around.

What are the tips you give for beginner to learn c# quickly?

Find a good book and start at the beginning.

I would recommend either Pro C# 2010 and the .NET 4.0 Platform or C# In Depth: Second Edition

What are the factors to be considered when moving from c,c++ to c#?

Know the naming conventions and differences of each.

C/C++ gets compiled to native code. C# gets JIT compilation.

C# has memory management. C/C++ doesn't (at least not the same).

C is not an object oriented langauge. C++/C# are, but each handles OO in a slightly different way.

Those kind of differences will change how you write/think about your code.

C# 4 is basically a superset of all the other versions, so if you know C# 4 then you definitely know the earlier versions. On the other hand, I think it's worth knowing what's in which version. I have a couple of "bluffer's guides" on my C# in Depth web site which give a bit of information about C# 2 and 3 - I'll do a similar one for C# 4 soon. See this question for a very brief list of features in each version.

As for migrating from C and C++ - try to ignore everything you think you know. Some bits will be similar, some will be completely different. You should try to work the way the language expects you to, rather than applying C++ idioms to it.

You might want to read Essential C# 4.0, C# 4.0 in a Nutshell or Accelerated C# 2010. My own book - C# in Depth - will have a second edition soon, covering C# 4, but it's really designed for people who already know C# 1.

I need to capture video from a webcam. Are there any classes in C#/.NET that can help me with this. I am only interested in real time data.

And are there any good C#/.NET books that I can study to gain deep knowledge on the language and the platform?

I would recommend you to use 3rd party library. It would be the best solution instead of inventing your own bicycle. Here, I used AForge.Net. Though it has some problems concerning performance, but I tweaked the library myself when performance became a critical issue for me. The AForge.Net code is open source and you can tweak it to your needs.

As for books you definitely should look at Jeffrey Richter's "CLR via C#" and John Skeet's "C# in Depth".

I have some .NET 1.1 websites that need to be converted into 4.0. I don't want to change the functionality or the design I just want them to be converted to 4.0 so that future edits can be made easily as working in 1.1 is not easy. What is the beast approach that I should follow for this purpose.

Don't forget to read Microsoft .NET Framework 1.1 and 2.0 Compatibility.

After that, be sure to check .NET 4.0 migration issues document.

Read C# in Depth from Jon Skeet that describes all new features for each version of C#.

I've been reading Jon Skeet's C# In Depth: Second Edition and I noticed something slightly different in one of his examples from something I do myself.

He has something similar to the following:

var item = someObject.Where(user => user.Id == Id).Single();

Whereas I've been doing the following:

var item = someObject.Single(user => user.Id == Id);

Is there any real difference between the two? I know Jon Skeet is pretty much the c# god so I tend to think his knowledge in this area is better than mine so I might be misunderstanding something here. Hope someone can help.

The queries should be equal when the tree is evaluated, however depending on the target the actual execution could differ (IE L2S optimization).

If I have a class and it's essentially just a bunch of variables - has no methods, really more of a storage space - is it better to convert it to a struct?

What is the "rule" for when to use a struct and when to use a class?

From Effective C#

Value types or reference types? Structs or classes? When should you use each? This isn’t C++, in which you define all types as value types and can create references to them. This isn’t Java, in which everything is a reference type (unless you are one of the language designers). You must decide how all instances of your type will behave when you create it. It’s an important decision to get right the first time. You must live with the consequences of your decision because changing later can cause quite a bit of code to break in subtle ways. It’s a simple matter of choosing the struct or class keyword when you create the type, but it’s much more work to update all the clients using your type if you change it later.

It’s not as simple as preferring one over the other. The right choice depends on how you expect to use the new type. Value types are not polymorphic. They are better suited to storing the data that your application manipulates. Reference types can be polymorphic and should be used to define the behavior of your application. Consider the expected responsibilities of your new type, and from those responsibilities, decide which type to create. Structs store data. Classes define behavior.

From C# in Depth

Suppose you’re reading something fantastic, and want a friend to read it too. Let’s further suppose that it’s a document in the public domain, just to avoid any accusations of supporting copyright violation. What do you need to give your friend so that he can read it too? It depends entirely on what you’re reading.

First we’ll deal with the case where you have real paper in your hands. To give your friend a copy, you’d need to photocopy all the pages and then give it to him. At that point, he has his own complete copy of the document. In this situation, we’re dealing with value type behavior. All the information is directly in your hands—you don’t need to go anywhere else to get it. Your copy of the information is also independent of your friend’s after you’ve made the copy. You could add some notes to your pages, and his pages wouldn’t be changed at all.

Compare that with the situation where you’re reading a web page. This time, all you have to give your friend is the URL of the web page. This is reference type behavior, with the URL taking the place of the reference. In order to actually read the document, you have to navigate the reference by putting the URL in your browser and asking it to load the page. On the other hand, if the web page changes for some reason (imagine it’s a wiki page and you’ve added your notes to the page), both you and your friend will see that change the next time each of you loads the page.

The differences we’ve seen in the real world form the heart of the distinction between value types and reference types in C# and .NET. Most types in .NET are reference types, and you’re likely to create far more reference than value types. The most common cases to know are that classes (declared using class) are reference types, and structures (declared using struct) are value types. The other situations are as follows:

Array types are reference types, even if the element type is a value type (so int[] is still a reference type, even though int is a value type).

Enumerations (declared using enum) are value types.

Delegate types (declared using delegate) are reference types.

Interface types (declared using interface) are reference types, but they can be implemented by value types.

Now that we have a basic idea of what reference types and value types are about, we’ll look at a few of the most important details.

I'm trying to retrieve a boolean from a hashtable... my code looks something like this:

Hashtable h = new Hastable();


h["foo"] = true;


object o = h["foo"];
if( o == null ) { return false; }
if( o.GetType() != typeof(bool) ) { return false; }
return (bool)o;

In contrast I use something like this for objects

return h["foo"] as MyObject;

Is there a nicer solution for booleans?

Don't use Hashtables. Those have been obsolete for seven years, since .NET 2.0 came out. Use a generic collection, like a Dictionary, instead.

Dictionary<string, bool> myDict = new Dictionary<string, bool>();
myDict["foo"] = true;

bool myBool = myDict["foo"];

Generics are seriously wonderful. Do yourself a favor and spend a few hours looking into them. You might start here, with MSDN, and I really enjoyed Jon Skeet's book, C# in Depth, that covers the topic... in depth.

For C++ I've always been using Boost.Functional/Hash to create good hash values without having to deal with bit shifts, XORs and prime numbers. Is there any libraries that produces good (I'm not asking for optimal) hash values for C#/.NET? I would use this utility to implement GetHashCode(), not cryptographic hashes.

To clarify why I think this is useful, here's the implementation of boost::hash_combine which combines to hash values (ofcourse a very common operation when implementing GetHashCode()):

seed ^= hash_value(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);

Clearly, this sort of code doesn't belong in the implementation of GetHashCode() and should therefor be implemented elsewhere.

Unless you have very specific requirements you don't need to calculate your type's hashcode from first principles. Rather combine the hash codes of the fields/properties you use for equality determination in one of the simple ways, something like:

int hash = field1.GetHashCode();
hash = (hash *37) + field2.GetHashCode();

(Combination function taken from §3.3.2 C# in Depth, 2nd Ed, Jon Skeet).

I am newbie to LINQ/XML. I just learned that Language integrated queries can be used for parsing xml. I am trying to parse the following XML structure and I need help



  <tp name="abc">yes</tp>
  <tp name="aee">no</tp>
  <tp name="bbc">no</tp>
  <tp name="ccb">yes</tp>

  <tn name="kjh">

  <tn name="klm">

  <tn name="hhh">

  <tp name="lml">no</tp>
  <tp name="rre">yes</tp>
  <tp name="rst">no</tp>
  <tp name="wee">yes</tp>

  <tn name="adf">

  <tn name="ddd">

  <tn name="kjj">



Output needed :

My objective is to show the above data as key value pairs by the category in a text file or a data grid etc.

abc : yes
aee : no
bbc : yes


kjh: 44 , 98
klm: 55 , 88
kjj: 92 , 98
ddd: 42 , 92

The code I have written so far is,

static void QueryTheData(XDocument doc)
                var a = doc.Descendants("config").Elements("params");
                var b = doc.Descendants("config").Elements("nits");

                var c = doc.Elements("tp");
                var d = doc.Elements("tn");

               /* to do :  parse the elements into key value pairs */
               /* Need hint or help to proceed to get key value pairs from xml data

             catch(Exception e)

ANy good pointers for beginner's LINQ/XML C# is also needed.

thanks in advance, ak

Jon Skeet's answer will do the trick for selecting the params part of your output.

Any good pointers for beginner's LINQ/XML C# is also needed.

I recommend C# in Depth, Second Edition, by Jon Skeet. This is overall a great C# book, and it includes some LINQ to XML material. While you're waiting for the book to arrive, and as a LINQ to XML supplement to the book, I'd recommend Microsoft's LINQ to XML documentation.

I have a collection of objects:


These objects support an interface IShape but i am getting an error trying to pass this into a function that is asking for:

  1. Why can't I pass this in?
  2. Is there any workaround to convert one to the other to get this to work?

In .NET 4, this should be supported, as IEnumerable<T> is declared to be covariant, i.e. the declaration is really IEnumerable<out T>. In .NET 3.5, that is not the case, and you would need to use a workaround such as


(It's worth noting this was a language feature evolution as well; that is, if you somehow were able to use C# 3 with .NET 4, it would still not work, because support for co- and contravariance was not added to C# until version 4 of the language.)

An excellent explanation of co- and contravariance can be found in Jon Skeet's C# in Depth, section 13.3.

I've been coding c# for close to 4 years now (vb.net before that) in an ASP.NET web forms environment. I've got the basics down but there are some things that I sometimes see that confuse me (interfaces, IEnumerable, IQueryable, reflection, etc..) that I'd like to grasp. I'm currently using c# 3.0 and will probably be moving to c# 4 in the next year or so. I'm currently learning MVC.

At my point in my programming career, what books, blogs, or resources could you guys recommend? Thanks!

ASP.NET MVC beginners book get ASP.NET MVC 2.0 cookbook. Its just for beginners and to learn core concepts of asp.net mvc 2.0 its very good.

Go deep. Read up and understand the internals of how the CLR works:

CLR Via C#, Third Edition by Jeffrey Richter

And understand the latest\greatest C# language features:

C# in Depth, Second Edition, by Jon Skeet

Don't be stuck only in C# and .NET; think about the bigger picture of computing, that's what I've done. Algorithms are the most important, as they govern how things like IQueryable and the other sorting interfaces work.

Algorithmics: The Spirit of Computing (3rd Edition)

Also worth looking at:

The Architecture of Computer Hardware and Systems Software: An Information Technology Approach

These are some course material I've come by, and I've really enjoyed them so far. I also am a big fan of C#, but I've benefited from getting down (low level) and dirty with these books.

One other one worth mentoning is:

Engines of Logic

This covers the history of computing and software, via some mathematical geniuses from the last century and before. People like Liebniz and Goedel, Von Neuman and Alan Turing.

Hope you find something interesting there. It's a bit off-topic for C# but for flexing the computer brain muscles, they're really good.

"...defines the syntax, order of evaluation of operands and operators, and the meaning of expressions."

of course...


I almost forgot...

var keys = m_ASPxGridView.GetCurrentPageRowValues("ID", "SID");
var selectedkeyValues = m_ASPxGridView.GetSelectedFieldValues("ID", "SID");

var unselected=keys- selected values

var unselected=keys.Except(selectedkeyValues)// does not work

Is it possible to write a linq query to get all the values from keys not [present in selectedkeyValues ?

Everything that BrokenGlass and pst have said is correct, but it seems there's still some confusion, stemming from the fact that these DevExpress methods return a List<object>, where object is:

An object which is an array of field values (if several field names are passed via the fieldNames parameter) or a direct field value (if a single field name is passed via the fieldNames parameter). (Source Link)

So, since you're passing multiple field names, code like this should work:

// Get the current values
var currentRowValues = m_ASPxGridView.GetCurrentPageRowValues("ID", "SID")
    // Cast each object to an array of objects
    // Project the two members of the array into an anonymous type
    .Select(x => new { ID = x[0].ToString(), SID = x[1].ToString() });
var selectedRowValues = m_ASPxGridView.GetSelectedFieldValues("ID", "SID")
    // Cast each object to an array of objects
    // Project the two members of the array into an anonymous type
    .Select(x => new { ID = x[0].ToString(), SID = x[1].ToString() });

// Compare the two collections to get the unselected row values
var unselected = currentRowValues.Except(selectedRowValues);

As we've been discussing, .NET won't know how to compare the two collections if they're of type object. However, it should work if they've been projected (using Select) to the same anonymous type -- I think by default it will use value-type equality.

Edit: According to Jon Skeet from C# in Depth:

Within any given assembly, the compiler treats two anonymous object initializers as the same type if there are the same number of properties, with the same names and types, and they appear in the same order.


Equality between two instances of the same anonymous type is determined in the natural manner, comparing each property value in turn using the property type's Equals method.

So, if I'm reading it right, the above code should do exactly what you're asking. Please let me know if I'm not ;-)

Possible Duplicates:
Beginning C#
The Definitive C++ Book Guide and List
How to start programming from scratch?

I'm currently trying these programming languanges but I dont' know where to find my resources.Please help me guys.

One of the best C# books I know is C# in depth

PluralInsight has great video tutorials.

I have been searching online for a neat way to compile code at runtime and manipulate the running application's objects (properties etc.). I have come across Snippy, CodeDom and CSharpCodeProvider but I didn't completely understood how I can use those solutions in my application to do what I want. Bottom line is, I want to have a small portion of the code in an external file so I can swap out different code during run time (e.g. Formulas to manipulate Data and etc.) Could somebody explain to me how exactly can I implement this in a WPF application in a neat fashion? I just need to pass the external code some data and after execution it will return me some data that I can populate an object with. P.S: I also thought about parsing Mathematical expression from String and manipulate my data that way but if I can parse and execute C# code externally at run time, it will give me much more freedom and control over the formula and data. Thanks in advance.

I think you would do better using .NET compatible dynamic language like IronPython or IronRuby. Those integrate pretty much seamlessly with C#/.NET and are actually designed to provide execution-time scriptability.

Trivial example of IronPython usage from Jon Skeet's C# in Depth:

// the python code
string python = @" 
text = 'hello' 
output = input + 1 

// setup the scripting engine
ScriptEngine engine = Python.CreateEngine(); 
ScriptScope scope = engine.CreateScope(); 
scope.SetVariable("input", 10); 
engine.Execute(python, scope); 

// the results

Needless to say, the scripts can use .NET Base Class Library and any extra methods you expose to them.

I'm fluent in HTML and CSS and decided to start learning asp.net. I understand the concept of programming and have started to learn to basics of c#; I know that the razor view engine is based on the c# Programming language, but should I start learning razor before fully grasping all concepts of c#?

Even though there's alot of synergy going on between C# and Razor, I think I'd recommend you get more comfortable with C# first and then try to get into ASP .NET MVC 3+. Also, the MVC structure will be new to you and you might find it overwhelming to tackle both at once.

Jon Skeet has a great introductory series on C# 4.0 that you may enjoy.

If you'd prefer a book over a video (as some do) then I'd recommend this one

Also, for the future, if you like Jon's C# video, Tekpub also has a good ASP .NET MVC video you could likely step right in to.

I've decided to start learning C#, but all the tutorials I can find are very dry and speak to the reader as if the reader is a machine.

How about some tutorials that talk to me like I'm a human?

In that case probably the best tutorial source would be a book. The tutorials you will find online are very generalized and usually intend to teach the reader how to accomplish a specific task. The worst thing about online tutorials is the fact that those are not structured. Therefore, as you go, you can get confused on what to learn next.

I would recommend starting with Pro C# 2010 and the .NET 4 Platform, Fifth Edition by Andrew Troelsen. It starts with the basics and goes on to more complex elements in a very structured way, so you learn step-by-step. You can also try tackling C# in Depth by Jon Skeet - it is one of the best books you can currently find on C#.

One more thing - the best way to learn a language in my opinion is not by tutorials but by having small tasks and trying to accomplish them. For example, you want to learn how to write to a text file. You research this topic and eventually you find out more about the whole process and why it works the way it does. The syntax understanding comes with this as well.

I've this question about pass some instances by ref or not: here is my problem:

Case 1: simple var like int:

private void button2_Click(object sender, EventArgs e)
    int nTest = 10;

    // this message show me 10

    testIntRef(ref nTest);
    // this message show me 11

private void testInt(int nn)

private void testIntRef(ref int nn)

this is exactly what I think, if I use the ref, the parameter is passed by reference, so if is changed, when I exit from the function, the value is changed...

Case 2: class:

// simple class to understand the reference..
public class cTest
    int nTest;
    public cTest()

    public void setTest(int n)
        nTest = n;

    public int getTest()
        return nTest;

// my main code
private void button3_Click(object sender, EventArgs e)
    cTest tt = new cTest();


    // I expect that the message shows me 2, 'cause testClass
    // doesn't have (ref cTest test)

private void testClass(cTest test)

and, as written in the comment on the code, I don't have passed my cTest as reference, but the result is the same, the message show me 55 and not 2..

How can I pass a class without reference?

How can I pass a class without reference?

You can't.

You can clone that instance and send it, but it will still be sent by ref...

  • class - Reference type
  • struct - Value type.


Quoting Jon Skeet C# in depth second edition:


This is probably the most widely propagated myth. Again, the people who make this claim often (though not always) know how C# actually behaves, but they don’t know what “pass by reference” really means. Unfortunately, this is confusing for people who do know what it means. The formal definition of pass by reference is relatively complicated, involving l-values and similar computer science terminology, but the important thing is that if you pass a variable by reference, the method you’re calling can change the value of the caller’s variable by changing its parameter value. Now remember that the value of a reference type variable is the reference, not the object itself. You can change the contents of the object that a parameter refers to without the parameter itself being passed by reference. For instance, the following method changes the contents of the StringBuilder object in question, but the caller’s expression will still refer to the same object as before:

void AppendHello(StringBuilder builder)

When this method is called, the parameter value (a reference to a StringBuilder) is passed by value. If I were to change the value of the builder variable within the method—for example, with the statement builder = null;—that change wouldn’t be seen by the caller, contrary to the myth.

C# in depth Value types and reference types page 46


The above code explains in simple terms about Action and Func. Still I am not getting what it is for 100%. Or not able to make the code work for me.

public void SteamVegetable(Vegetable vegetable, int timeInMinutes)
    CookVegetable(vegetable, Steam, timeInMinutes);

public void FryVegetable(Vegetable vegetable, int timeInMinutes)
    CookVegetable(vegetable, Fry, timeInMinutes);

public void BakeVegetable(Vegetable vegetable, int timeInMinutes)
    CookVegetable(vegetable, Bake, timeInMinutes);

public void CookVegetable(Vegetable vegetable,
   Action<Vegetable, CookingTime> cookingAction,
   int timeInMinutes)
    cookingAction(vegetable, Minutes.Is(timeInMinutes));

Can someone help me to convert the code from vegetable to numbers and Steam --> Addition, Fry --> Multiplication, Bake --> subtraction when two operands are passed to it.

When I see the code working I can understand it better.

I might be wrong in understanding what you want, but I'll try to answer it. Note, that I omit many complex things in example, like I would use generics instead of plain int values, but this will just create redundant complexity in the example.

In example below I just define high-order function, which takes two int values, function, that transforms two values into string (i.e. encapsulate some behavior) and them embrace this result into enclosing and opening tags, one of which is passed in. Note, that I assume you are familiar with lambda notation in C#.

ApplyAndPrettyPrint(100, 3, "summ of 100 and 3 is equal to: ", (x,y) => (x*y).ToString("N0"));
ApplyAndPrettyPrint(100, 3, "100 to power 3 is:  ", (x,y) => (Math.Pow(x,y)).ToString("N0"));
ApplyAndPrettyPrint(2, 33, "2 * root of 33 is:  ", (x,y) => (x * Math.Sqrt(y)).ToString("N0"));

public void ApplyAndPrettyPrint( int firstNumber, int secondNumber, string startTag, Func<int, int, string> evaludationFunction) 
    string result = startTag;
    result += evaludationFunction(firstNumber, secondNumber);
    result += ";";
    Console.WriteLine (result);

So that Func here is used like a box, with two integers as input and one string as output.

Second example shows how we can pass Action into method, that will be evaluated over some array of numbers. Again, I omit details of IEnumerable interfaces and generics.

int[] numbers = new []{ 1, 2, 4, 5, 6, 7 };
ApplyForEach(numbers, (x) => Console.WriteLine ("square of {0} is {1}", x, x*x));

public void ApplyForEach(int[] numbers, Action<int> someFunction)
    foreach (var number in numbers)

The result will just print squares of integers with some descriptive chars. In other word Action is delegate with no outputs. You can think of them as box with some inputs, but with no outputs at all.

Hope that this will do the trick for your understanding. The bottom line is that the only difference between delegate types of Action and Func is the semantics of the last generic type: in Func it is the returning value, in Action returning value is void, so last generic type just goes to input parameter.

If you find this topic somewhat difficult, Jon Skeet describes delegates within Chapter 5 "Fast-tracked delegates" in his marvelous book "C# in Depth"

I came to here from a friend of mine that, to master the C# language, one must go through the ECMA C# spec. Is this true?

The ECMA spec is sadly out of date. Reading the annotated MS spec is useful, but not essential. Really, just use C#... lots. And read books like C# in Depth.

My company has asked me to take Exam 70-573 on SharePoint 2010 Application Development.

So the first step for me is to learn C#. Can you guys recommend any books that will help me learn what I need to know so that I can move into learning SharePoint development. Also, should I spend time learning about the .NET framework itself?

I have a lot of programming experience and am good at picking up new languages. I've just never done any .NET development before.


Jon Skeet's book is the best way to learn C# regardless of how you'll use C# or what exam you might want to pass.