Silverlight Hack

Silverlight & related .NET technologies

About Me

Welcome to Silverlighthack.com.  This is a site where you can find many articles on Silverlight, Windows Phone 7 and .NET related technologies.  

My name is Bart Czernicki.  I have been working with computers since 1988 and have over 12 professional years in the IT field focusing on architecture, technology strategy and product management.  I currently work as a Sr. Software Architect at a large software development company.

Below is the cover of my new book that shows how Silverlight's unique RIA features can be applied to create next-generation business intelligence (BI 2.0) applications.

Silverlight 4 Business Intelligence Soft 

Contact: bartczernicki@gmail.com

View Bart Czernickis profile on LinkedIn

NONE of the comments or opinions expressed here should be considered ofmy past or current employer(s).  The code provided is as-is without anyguarantees or warranties.

Silverlight 2.0 - Concepts To Become A Silverlight Master (Series Part 2 - WCF)

Series update: I changed the name of the series as the name was slightly confusing.

Series Articles:

Silverlight 2.0 technology is based on a web plug-in that runs on the client's computer.  Writing applications/tools/games that don't depend on data is straightforward and doesn't require the Silverlight developer to think much beyond the client's domain.  However, what if the developer wants to introduce external data into their Silverlight 2.0 application?

First, the bad news:

  • Silverlight 2.0 currently runs on a small subset of the .NET 3.5 Framework.  This means some of the "direct" data channels/communication libraries are not available to you (i.e., remoting, COM, database, etc.)
  • Silverlight hosts its app domain on the client's workstation.  This means that even though it is a web technology hosted on a web server, it can't leverage resources on the web server that do not cross the web server domain (i.e., database calls, local dll files that call a database, local dll files that consume a service)
  • Another limitation is that because Silverlight utilizes a minimal/secure plug-in architecture, you cannot access local workstation data channels easily.  For example, a fat client windows application can call a database, windows/web services, make remote calls, etc.  Most of these (as you guessed it) are not available to you.

So HOW can I consume some data from an external data source?  Silverlight 2.0 Beta 2 currently supports these communication channels:

As you can see from the list above, Silverlight 2.0 (as of Beta 2) supports a variety of communication mechanisms.  Most of these, excluding Sockets/JavaScript-bridge, focus on service technology.  Therefore, as a developer, you can talk to the data store inside your service application and expose it via any types of these services.  Consuming these services can be done several ways, but that is not the focus of this article. Designing these services can be done several ways as well. 

As a developer, what is the best way to design services that a Silverlight plug-in client can consume? Luckily, this is where WCF comes in (Finally, the meat of the article).

WCF is an acronym for the Windows Communication Foundation, which was introduced in .NET 3.0.  WCF (like LINQ/.NET) is one of these technologies that is hard to summarize in one good definition.  Some developers simply say WCF is web services or a way to design SOA. My definition of WCF is actually not mine.  This definition is from Juwal Lowy's forward from his great book Programming WCF Services:

"WCF is a fundamental technology that provides an easy and clean way to generate services and applications in compliance with what I regard as sound design principles."

WCF (without going into too much detail) allows you to architect applications by applying best practice guidelines automatically.  Security, throttling, opt-in serialization, logging, etc., are handled for you just by creating a service inside the WCF framework and setting config/attribute values.  Juwal Lowy (in web casts/book/classes) says you can spend time writing plumbing code and trying to adhere to best practices or use WCF and allow it to do the majority of the work for you. 

Silverlight runs on a subset of the .NET 3.5 framework, so it does not support all of the WCF bindings and can't consume every type of WCF binding/endpoint.  However, from the list above utilizing WCF (as your service engine) you can design: SOAP 1.1 Services, Duplex Services, AJAX Enabled Services & REST Services.  All of these can be consumed by the Silverlight 2.0 client.

A great aspect of WCF is that it allows you to write your application and expose it using various binding endpoints supported by Silverlight.  Furthermore, existing WCF services can simply be "Silverlight enabled" by providing a compatible Silverlight endpoint.  Depending on the functional requirement, of course, this might not be possible. 

The diagram below demonstrates the same services being consumed by different clients using different endpoints:

 

Quickly doing a search on services+Silverlight, you will notice that WCF comes up a majority of the time.  Microsoft is pushing WCF heavily as a best practice for writing services for Silverlight.  In fact, after installing the Silverlight 2.0 SDK, you have a new template called "Silverlight-enabled WCFService" for quickly creating WCF services that can be consumed with Silverlight. 

Silverlight 2.0 Beta 2.0 allows the developer to configure the WCF service inside a ClientConfig file.  This is a real nice add for additional configuration of WCF services, especially if you are a software vendor that needs to change connections/tweak settings for different deployments declaratively.

WCF (in .NET 3.5) has great support for creating RESTful services.  RESTful services are used all over the place: Flickr, MySpace, Amazon, etc.  WCF allows you to quickly create low/high REST services that can use XML, JSON or RSS encoding.  Silverlight can consume these easily.  In fact, many examples online show this by communicating with external REST services and manipulating the data on the client (i.e., using LINQ).

Summary of benefits using WCF to consume data in Silverlight:

  • All the different Silverlight service types can be designed with the single WCF technology.  Basically, anything you can do with other service design you can do with WCF.  However, with WCF you are doing it with a single technology
  • Allows the developer to design services focusing less on implementing best practices and plumbing code (WCF's biggest selling point, since it does a lot for you out of the box)
  • WCF endpoint abstraction allows the developer to create service endpoints for both Silverlight and non-Silverlight consumers (while sharing the same code)
  • Microsoft recommended best practice.  WCF includes first class support in Silverlight: online examples, Silverlight-enabled WCF service template and clientConfig XML configuration file
  • Best practice for the future.  As Microsoft adds additional support to the Silverlight service stack, developers can be assured that probability-wise this will be done via WCF.  For example, Duplex services (introduced in Beta 2)

In summary, Silverlight and WCF technologies complement each other very well.  WCF is a single technology that provides you a single design mechanism to create a variety of solutions for exposing your data to a Silverlight client.  WCF is not a requirement in order to consume data inside Silverlight (lots of examples online with 3rd party REST services).  However, because of how well it works with Silverlight and deprecates other SOA design (at least in the MS world), it is a no-brainer that WCF is recommended by Microsoft.  In my opinion, WCF is a technology every developer needs to master in order to be effective with consuming data inside Silverlight.

Posted: Jul 20 2008, 13:49 by Bart Czernicki | Comments (8) RSS comment feed |
  • Currently 3.714286/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: Silverlight | WCF
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us

Silverlight 2.0 - Concepts to become a master series (Part 1 - .NET/C#)

Intro

Silverlight is THE next generation rich web technology to learn if you are a programmer focusing on delivering web content.  There are many articles out there on how to get started or how to write your first Silverlight program.  However, many of these articles fail to address the specific knowledge you need to master to be a truly effective Silverlight programmer.

Silverlight, just like any technology, has a concrete matrix of concepts a programmer should focus on in order to be able to call himself a master of the technology.  Fifteen to twenty years ago (before the web, before mobile technology, before networks were prevalant, etc.), you could have an almost complete grasp of software engineering by focusing just on a few skills.  As software engineering started to mature and the web blew the door off the amount of new technology/processes/patterns available, it became impossible to be an expert in every single facet of software development.  Silverlight is just a small thing right now in the bag of technologies available for developers to learn.  However, the Silverlight technology demands that you are productive with certain concepts in order to become an effective developer with the technology.  Learning a new technology like Silverlight can be a daunting task with the limited R&D time developers are afforded.  Furthermore, not knowing which technologies Silverlight relies on to deliver complete solutions can definitely pose a challenge in trying to learn on your own blindly.

I have been working with Silverlight since Alpha 1.1 -> Beta 2 (on and off; mostly on since Beta 1) and there are certain subject matters that demanded my deep understanding in order to use them effectively in Silverlight.  Instead of creating a massive post, I decided to create a series of posts about the core concepts a Silverlight developer needs to focus on.  The goal of the article is to help developers getting started with Silverlight 2.0 understand what technologies they should get familiar with or which technologies to brush up on in order to learn Silverlight in the most efficient way.

Series Articles:

 

 

.NET 3.5/C#

Silverlight 2.0 is a Microsoft technology platform.  Like all new Microsoft platforms, in order to develop on it, you have to know .NET.  That's a given.  Silverlight 2.0 runs on a subset of the .NET 3.5 framework which has a very small footprint.  However, the Silverlight team managed to add a great deal of libraries (even lots of .NET 3.5 items) inside this sub system.  Obviously, I don't think this comes as a shock to anyone that in order to program in Silverlight 2, you will be developing on .NET.  Since you will be coding in .NET, it also makes sense that you will be coding inside Microsoft's flagship IDE Visual Studio.  Visual Studio 2008 has great integration with Silverlight 2.0 with debugging/design/projects, etc.  This is one of Microsoft's strong points.  Architects/Sr. Developers debate platforms/languages (dynamic/functional/OOP), etc. all the time.  However, what is not debatable is the fact that Microsoft Visual Studio is one of the best programming environments out there.  Visual Studio/.NET are pretty much a requirement...no shockers here.

What is controversial is my opinion that your .NET language of choice should clearly be C#.  Silverlight 2 is currently in Beta 2 release.  For the most part, I find that the early adopters of any new technology are usually advanced developers.  Like it or not, that trend usually applies to C# development over VB.NET.  Let's take some examples:

  • If you right now want to find an article about Silverlight and a code example, the chances are 85%+ that this example will be exclusively in C#.  Does that mean VB.NET developers can't learn Silverlight?  No, I am simply saying that you have a MUCH easier time as a C# developer if you are reading examples in your native/favorite language.
  • The absolute best resource when learning a beta technology is blogs.  Bar none. The Silverlight 2 books are just starting to come out in "beta" and Microsoft's own libraries are just starting to be populated and are not a great resource yet.  However, blogs are great for beta technology as they allow you to overcome bugs/issues/undocumented concepts, etc. that plague beta releases.  Most advanced bloggers blog in C#.  This ties into my previous assertion that more advanced programmers prefer C#.  Furthermore, C# has many shortcuts that allow bloggers to post clear/concise code while getting the point across.  This is yet another advantage C# bloggers use when posting about Silverlight.  Check out some samples on Jesse Liberty's blog, Tim Heuer's blog , etc.
  • Magazine articles are your next best friends.  They are dominated by C# syntax as well.  I subscribe to ASP.NET and Code magazine (I used to get MSDN Mag when I had a MSDN Sub) and a majority of the code is in C#.  Note: The only time I have seen a real master coder write in VB.NET almost exclusively was Dino Esposito.  I do think though after he went to idesign, Juwal Lowy straightened him out, as he has now been posting in C# :)
  • Microsoft documentation is 50/50 C# and VB.NET.  Obviously, this case is a draw.

I am not saying that you cannot learn Silverlight without C#; just that I have found that it makes my life a lot easier.  Imagine you are a VB.NET developer working on an issue and you are ready to throw something and you try to enter your problem into Google.  The search engine pops up with a solution and then you see the delegate word being thrown around (anon methods) or the => symbol.  Obviously you will have to decipher the syntax first before proceeding.  Furthermore, I think as you become more senior with the C# advanced syntax, it actually becomes HARDER to read VB.NET.  I completely disagree with MS's position that it doesn't matter.  As the RTM approaches, this might change as more books appear (this tends to still favor C#, but less percentage-wise).

If you are just getting started in .NET by being drawn to Silverlight, I think you will have a much easier time learning Silverlight if you learn C#.  Doing so will give you access to many more current samples/projects online in a native language. 

Posted: Jul 15 2008, 13:41 by Bart Czernicki | Comments (7) RSS comment feed |
  • Currently 3.75/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: Silverlight
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us

Evolution of C# delegate syntax from .NET 1.x to 3.5

Delegates were introduced with C# 1.0 (with .NET 1.0) as a way to represent function pointers.  Delegates like most other aspects of advanced C#/.NET programming were often misunderstood and a lot of times programmers didn't even know they were using them inside their code! One source of this problem was a rather cluggy syntax provided with the original C# 1.0 syntax.  Luckily as .NET evolved, so did the syntax for delegates by becoming more concise and clear.  This is exactly what this article focuses on; this is NOT an intro into delegates, how they relate/work with events or a "best practice" guide.

The best way to show delegate syntax in action is to try to solve a simple coding problem with them.  Suppose I get asked this on an interview: I have a form with 2 text boxes and I can input 2 numbers.  What I would like to do is when I click the "=" button (equals) is have the numbers be added via a delegate binary operation, by adding the two numbers.

So the form looks something like this:

Let's assume that we have an event handler already hooked up to the button and after we click that button we expect the two numbers to be added.

.NET 1.x (1.0 - 1.1) Solution (C# 1.0)

This solution has four parts:

  • Declare the delegate with the desired signature
  • Declare a method that matches the delegate signature
  • Instantiate the delegate (tell the delegate with method to call)
  • Call the delegate and retrieve the result
Delcare the delegate:

delegate int Add(int firstNumber, int secondNumber);

The delegate type is created by using the delegate keyword (much the same way we would declare a string type; i.e., string someString = "test";)  The second word is the return type for our delegate.  Since we are trying to add two numbers we expect to get a integer (int) back.  Next, is the name of the delegate.  In our case, we named the delegate Add (much the same way you would name a method).  Lastly, we need want our code to add two numbers together.  Therefore, we would like to have two interger parameters that are going to be passed from our text box. 

In the code above, what we did was create a template in a sense of how we want our method to look like.  We do not know what this method will do yet, but we do know it will have two integers as parameters and it will return an integer.

Declare a method that matches the delegate signature:

private int AddNumbers(int firstNumber, int secondNumber)

        {

            return firstNumber + secondNumber;

        }

Here we declared a method that matches the desired signature of our delegate type.  Our method is called AddNumbers and it takes two integer parameters and has a integer return.  The method is where our simple business logic of adding two numbers will occur and the method body will execute and give the delegate some kind of functionality (in our case add two numbers).

Instantiate the delegate (tell the delegate with method to call)

Add add = new Add(this.AddNumbers);

This piece of code will instantiate a new Add type and tell it to call the AddNumbers method.  Behind the scenes, the compiler compiles the delegate type we declared (code in "Declare the delegate") into a class.  This class can take a parameter for its constructor a method that matches the signature of the delegate.  It doesn't matter what the method is called or what the underlying business logic does. The only thing that matters is that the signature of the method matches the signature of the delegate.  To reiterate (in our case) this is a method that has 2 integer parameters with an integer return type.

Call the delegate and retrieve the result

int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

Calling the delegate is the simplest part.   Now that we have an instance of the delegate called "add", we simply pass in the two integer parameters.  Above, we have two text boxes and we convert each Text property into an integer and pass them into the instance of our Add delegate "add".  The delegate takes these parameters and simply calls the method it was told to in the step above and passes these paramters. 

For those confused, you can just call the delegate directly.  For example:

int result = add(3, 4);

As you will see below, all of the different types of using delegate code use the same way to call the delegate. This part of calling the delegate does not change, no matter what method you use!

Summary

Using delegates in .NET 1.0 - 1.1 (2002 - 2003) was not the friendliest.  There were a few steps to go through.  Many programmers taking the leap from VB.NET or another language simply by passed delegates because of the additional syntax.  Imagine learning a new language and trying to conceptualize using delegates and their uses.  Delegates in these early days of .NET were usually used/abused by C++ programmers familiar with the delegate C++ counterpart.  Delegates also in those days had some performance issues; design implications (making a public delegate is bad) and some designs could cause memory problems. 

Putting it all together would look something like this:

    1         // 1) Declare a delegate

    2         delegate int Add(int firstNumber, int secondNumber);

    3 

    4         // 2) Declare a method (matches the delegate signature)

    5         private int AddNumbers(int firstNumber, int secondNumber)

    6         {

    7             return firstNumber + secondNumber;

    8         }

    9 

   10         private void btnAdd_Click(object sender, EventArgs e)

   11         {

   12             // 3) Initialize the delegate to a method that matches the signature

   13             Add add = new Add(this.AddNumbers);

   14 

   15             // 4) retrieve the result

   16             int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

Not counting comments/whitespace it was about 7 lines of code to declare/initialize/call a delegate back in the .NET 1.x days. More importantly, you have 4 seperate parts to this solution.

.NET 2.0 - 3.0 Solution (C# 2.0)

.NET 2.0 introduced a concept called anonymous methods.  This allowed us to call inline business logic (i.e., a method) without having to have the method defined.  The business logic simply became part of the delegate.  Let's see how this improved our delegate syntax for our scenario. 

This solution has three parts:

  • Declare the delegate with the desired signature
  • Instantiate the delegate (with the business logic defined inside the delegate "body")
  • Call the delegate and retrieve the result
Delcare the delegate:

delegate int Add(int firstNumber, int secondNumber);

The delegate type declaration is the same as the prior version.

Instantiate the delegate (with the business logic defined inside the delegate "body")

Add add = delegate(int firstNumber, int secondNumber)

        {

            return firstNumber + secondNumber;

        };

We put the business logic now inside the "body" of the instantiation of the delegate. Notice how we skipped the method decleration in this solution, because it's not needed since it's inside the delegate "body". 

So, this is nice and clear and we eliminated a whole part (no more method to declare) and one statement of code.  This is what anonymous methods allow us to do, by putting the method logic directly inside the "body" of the delegate.  The syntax for the anonymous method starts with the word delegate itself after the equal sign.  In this case, it tells the compiler that we are declaring an anonymous method.  The next step is to define the parameters to match the signature of our Add method, which are the two intergers respectively.  Our inline body of our delegate is the same as our AddNumbers method returning an integer.  That's all there is to it.  Anonymous methods can have no parameters and as well can have no (void) returns.

Call the delegate and retrieve the result

int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

Same as before.  Nothing new to see here.

Summary

Using delegates in .NET 2.0 - 3.0 became simpler.  Not just because you eliminated one line of code, but because now it had one less "working part" and programmers not familiar with delegate syntax could easily tell what was going on.  This solution obviously would not work when you wanted to design more complex/re-usable objects.  However, it made the use of anonymous methods in predicates and simple situations much easier and the delegate syntax was finally resembling some brevity that functional languages enjoy. 

In summary, our .NET 2.0 - 3.0 solution looks like this:

    1         // 1) Declare a delegate

    2         delegate int Add(int firstNumber, int secondNumber);

    3 

    4         // 2) Initialize the delegate using an anonymous method(new in .NET 2.0)

    5         Add add = delegate(int firstNumber, int secondNumber)

    6         {

    7             return firstNumber + secondNumber;

    8         };

    9 

   10         private void btnAdd_Click(object sender, EventArgs e)

   11         {

   12             // 3) Retrieve the result

   13             int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

A lot more concise and we elminated 3 lines of code; 1 part (method decleration) and the code is a little clearer to read. 

.NET 3.5 Solution (Type 1) (C# 3.0)

.NET 3.5 (C# 3.0) introduces even more brevity to delegate syntax with lambda expressions.  Lambda expressions are a further evolution of syntax brevity for anonymous methods.  You take the spirit of declaring the business logic inline with delegates even further.  I broke the .NET 3.5 solution into type 1 and type 2.  Type 1 uses just uses the new lambda expression syntax.

This solution has several parts:

  • Declare the delegate with the desired signature
  • Instantiate the delegate (with the business logic defined inside the delegate "body")
  • Call the delegate and retrieve the result
Delcare the delegate:

delegate int Add(int firstNumber, int secondNumber);

The delegate type declaration is the same as the prior version(s).

Instantiate the delegate (with the business logic defined inside the delegate "body")

Add add = (firstNumber, secondNumber) => firstNumber + secondNumber;

Whoa!  That looks different.   Let's take a step back and see how we got to the lambda expression from the anonymous method. 

In the .NET 2.0 version we had something like this:

Add add = delegate(int firstNumber, int secondNumber)

        {

            return firstNumber + secondNumber;

        };

First, let's remove the delegate keyword.  Since the delegate keyword back in the .NET 2.0 (C# 2) version told the compiler we were declaring an anonymous method, it needs to be replaced since we want to use lamdba expressions.  Since we are going to replace the anonymous method syntax with lambda expression syntax, we need to use the keyword that tells the compiler we are working a lambda expression.  This keyword is "=>".  The compiler would like to see this after the parameters are defined but before the inline body of the expression. 

Our first step in our lambda expression will look like this (This is valid syntax and will compile):

Add add = (int firstNumber, int secondNumber) =>

        {

            return firstNumber + secondNumber;

        };

The expression now reads:  The parameters of integer firstNumber and integer secondNumber "goes to" return the sum of firstNumber plus secondNumber. The code above is now a fully functioning Lamdba Expression and not an anonymous method anymore.  Replacing the "delegate" keyword with the appropriate location for the "=>" keyword converted this from an anonymous method to a lambda expression.  This is very important, so the compiler with this simple keyword swap now knows we are dealing with a lambda expression.

We didn't really gain much here.  We essentially replaced one keyword with another.  What we can do next is add additional lambda expression shortcuts. Lambda expressions do not require curly braces or return type. 

If we remove both of these, this expression now becomes:

Add add = (int firstNumber, int secondNumber) => firstNumber + secondNumber;

That's getting much better.  Notice, no curly braces or the return keyword; the C# 3.0 compiler can derive all this information for us!  The expression looks more concise now.  But we can do better.  The compiler is even smarter now since it can detect the type of parameters we want to use.  We don't need to explicitly say that we are passing in two integers; this is detected by the compiler. 

Now the full expression (after removing the two int keywords) remains as just the parameter names:

Add add = (firstNumber, secondNumber) => firstNumber + secondNumber;

Call the delegate and retrieve the result

int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

Same as before.  Nothing new to see here.

Summary

We did a lot here.  Lambda expressions make a big difference in syntax brevity and clarity.  Let's take look what we have now:

    1         // 1) Declare a delegate

    2         delegate int Add(int firstNumber, int secondNumber);

    3 

    4         // 2) Initialize the delegate using a lambda expressions (new in .NET 3.5)

    5         Add add = (firstNumber, secondNumber) => firstNumber + secondNumber;

    6 

    7         private void btnAdd_Click(object sender, EventArgs e)

    8         {

    9             // 3) Retrieve the result

   10             int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

A lot more concise and we elminated 3 more lines of code!  Now we are getting somewhere. 

.NET 3.5 Solution (Type 2) (C# 3.0)

The type 2 solutions still utilizes lamdba expressions.  However, it also uses the new Func delegate.  A Func is a delegate type with several generic parameters defined.  There are 5 different Func delegates pre-defined for you with .NET 3.5.  Why are there 5 different ones?  This should cover you for most of your scenarios when designing methods/delegates, etc.  Usually if you are creating signatures of methods with more than 4 parameters, you probably need to refactor your parameters into an object.  '

For example, the Func that we need has to have 2 input parameters and a return parameter.  This one that is pre-defined in .NET will suit us great:

public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);

This solution has ONLY TWO parts:

  • Declare & instantiate the delegate (with the business logic defined inside the delegate "body")
  • Call the delegate and retrieve the result
Declare & instantiate the delegate (with the business logic defined inside the delegate "body") 

We already have a delegate (Func) with the required signature we need. It is a generic delegate; however, we can determine the types of parameters/result we need.  All we need to do is create a variable of this type and pass in the expression we created above (.NET 3.5 Type 1).  Our entire decleration/instatiation is in ONE line of code now:

Func<int, int, int> add = (firstNumber, secondNumber) => firstNumber + secondNumber;

Now that's nice concise syntax!.  All we did was declare a variable called add of type Func with 2 integer parameters and an integer return parameter (return type).  On the right-hand side of the equation we simply just use the lamdba expression from the example above.   

Call the delegate and retrieve the result

int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

Same as before.  Nothing new to see here.

Summary

This is as simple as you are going to get right now; a single line of code to declare/initialize a delegate with a lambda expression.

    1         Func<int, int, int> add = (firstNumber, secondNumber) => firstNumber + secondNumber;

    2 

    3         private void btnAdd_Click(object sender, EventArgs e)

    4         {

    5             // 2) Retrieve the result

    6             int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

This is as concise as you will get.  One line of code to rule them all :)

If you want to delve deeper, I would suggest picking up a C# 3 book.  I didn't really explain some of the origins of this code and some of the nuances with anonymous methods/lambda expressions or even delegates.  I just wanted to focus on the evolution of the C# syntax.  Attached is a simple VS 2008 solution zip that demonstrates the 4 different major -- there are lot more smaller permutations -- ways to write delegate syntax.  I broke the solution so that each type of code is in its own respective form (this way, every variable is named the same).  I also did not want to introduce any other C# constructs but wanted to strictly focus on the topic which was the syntax.

EvolutionOfDelegates.zip (55.06 kb)

Posted: Jul 14 2008, 17:09 by Bart Czernicki | Comments (0) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: .net
Tags:
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us

Welcome to SilverlightHack

This will be my authoratative blog primarily focusing on Silverlight, Business Intelligence, WCF, SQL Server and all the other good stuff I currently play with.  I have a back log of about 20-25 articles that I have written and notes that I think would be valuable to start sharing with the .net community.  I will start posting good articles [somewhat soon].
Posted: Jul 13 2008, 16:56 by Bart Czernicki | Comments (0) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under:
Tags:
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us