Search Eridotnet

 

Thursday, January 24, 2008

Quick thoughts on .NET 1.x, 2.0, 3.0 and 3.5 (part five: extension methods)

Ahh... I enjoy the comments on my other previous post, part three of my quick thoughts. I hope it really open the minds of Indonesian software developers about .NET progress and its current/latest features.

Now, I'm going to talk about extension methods. According to Visual C# 2008 (C# 3.0) documentation, extension methods are:

"Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type."

Yes, you can add methods to existing types. But this addition has its own requirements, not just simple "add".

Take look at this sample code in C# (from MSDN):

    /// <summary>
/// Extension methods must be inside of a public static class
/// </summary>
public static class StringExtension1
{
// This is the extension method.
// The first parameter takes the "this" modifier
// and specifies the type for which the method is defined.
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
    class Program
{
static void Main(string[] args)
{
string s = "The quick brown fox jumped over the lazy dog.";
// Call the method as if it were an
// instance method on the type. Note that the first
// parameter is not specified by the calling code.
int i = s.WordCount();
Console.WriteLine("Word count of s is {0}", i);
Console.ReadLine();
}
}

As you can see, String has additional method, WordCount(). It returns number of words in a hard coded sentence as a value of String s. There's no magic here, only the compiler can decide at runtime where to look for this method, after searching through static classes. The static classes doesn't have to be in the same namespace as your code. After it find the method, it translates into an execution of the static method of StringExtension1 class at runtime.


Still, the conclusion is, this is a proof that there's no change in CLR since CLR in .NET 2.0. A language features? No. It's more correct if you simply say it as a compiler feature. Why? Since it's more emphasized in compilation time.


The requirement of extension methods are (also as step by step guide, taken from MSDN):



  1. Define a static class to contain the extension method.
  2. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers (C# Programming Guide).
  3. Implement the extension method as a static method with at least the same visibility as the containing class.
  4. The first parameter of the method specifies the type that the method operates on; it must be preceded with the this modifier.
  5. In the calling code, add a using directive to specify the namespace that contains the extension method class.
  6. Call the methods as if they were instance methods on the type.
  7. Note that the first parameter is not specified by calling code because it represents the type on which the operator is being applied, and the compiler already knows the type of your object. You only have to provide arguments for parameters 2 through n.

The sample above is an extension method that has no parameter. What if I want parameters?


This is the sample:

    public static class StringExtensionParams
{
public static String Greetings(this String s, String name, string salutation)
{
StringBuilder sb = new StringBuilder();
sb.Append("Hello ");
sb.Append(salutation);
sb.Append(" ");
sb.Append(name);
sb.Append("! ");
sb.Append(s);
return sb.ToString();
}
}

This is the code that use Greetings:

    class Program
{
static void Main(string[] args)
{
string s = "The quick brown fox jumped over the lazy dog.";
// Call the method as if it were an
// instance method on the type. Note that the first
// parameter is not specified by the calling code.
int i = s.WordCount();
Console.WriteLine("Word count of s is {0}", i);
String str1 = DateTime.Now.ToLongDateString();
String str2 = str1.Greetings("Eriawan", "Mister");
Console.WriteLine(str2);
Console.ReadLine();
}
}

Pretty cool, isn't it? But one thing is, be careful with the name of the extension method. You can get errors if you extend some type that already has some extension methods with the same name somewhere else in your project.


 

Happy coding! Next blog stop: LINQ and Extension methods usage!



kick it on DotNetKicks.com

Tuesday, January 15, 2008

Quick thoughts on .NET 1.x, 2.0, 3.0 and 3.5 (part four)

Hi there! I'm back.

I can just declare variable without typing?


On my previous post on LINQ, I discussed quick overview of LINQ. If you read the code, there are many uses of "untyped" variable, I just used var in C# or Dim in VB.NET. This is also one of new features of VS 2008. This feature is known as "type inferencing".

Type inferencing sample in C#:

        static void Main(string[] args)
{
var i = 10;
var anytext = "anytext";
var anyarray = new int[]{ 1, 2, 3 };
Console.WriteLine("i= {0}", i);
Console.WriteLine("anytext= {0}", anytext);
foreach (var item in anyarray)
{
Console.WriteLine("array ={0}", item);
}
Console.ReadLine();
}

Type inferencing sample in VB.NET:

    Sub Main()
Dim i = 1
Dim anytext = "anytext"
Dim anyarray = New Integer() {1, 2, 3}
Console.WriteLine("i= {0}", i)
Console.WriteLine("anytext= {0}", anytext)
For Each item In anyarray
Console.WriteLine("array ={0}", item)
Next
Console.ReadLine()

End Sub

 

As MSDN of C# says:

"When used with local variables, the var keyword instructs the compiler to infer the type of the variable or the array elements from the expression on the right side of the initialization statement."

Also MSDN of VB.NET says:

"By using local type inference (also referred to as implicit typing), the compiler determines the data types of local variables based on the values that are used to initialize them."

Yes, they're both the same context and concept. The point is, the type inferencing is not .NET 3.5 new features. It's simply a language feature. But I decide to discuss it here since it's often in describing LINQ samples used throughout MSDN for VS 2008. Type inferencing can be used for primitive types such as integer, boolean, string. Complex types such as arrays and collections or just classes of IEnumerable are welcome.

So, don't worry. Your beloved .NET is still strongly typed. No messing around with real untyped variables, or your code won't compile.

OK, I have LINQ, type inferencing, what are other new features?


 

Many! On .NET 3.5 side, you have:


  • LINQ
  • Addins
  • Peer to peer networking
  • Integration of WCF and WF
  • 2D on 3D in WPF

On VS 2008 side:


  • Split view editor for ASP.NET designer
  • Fully released and supported WPF Designer (formerly known as "Cider")

On both Visual C# and VB.NET:



  • Type inferencing
  • Lambda expressions
  • Extension methods
  • LINQ as a language service/feature

On VB 2008 (a.k.a. VB.NET 9.0) side only:


  • XML Axis Properties
  • XML Literals
  • Anonymous type (almost similar to C# object initializers, but only restricted to anonymous type, not collections)
  • Relaxed delegates

On Visual C# 2008 (a.k.a. C#3.0) side only:


  • Partial method (only valid for methods that return void)
  • Auto-implemented properties with backing field automatically generated
  • Object initializers, enables object initialization without explicit calls to a constructor.
  • yield keyword
  • Anonymous methods

Next post? I'll try to discuss Lambda expressions on C# and VB.NET.

Tuesday, January 8, 2008

Quick thoughts on .NET 1.x, 2.0, 3.0 and 3.5 (part three)

Now, the top "buzzword" for .NET 3.5: LINQ. Yes, it's here, released. It's not for VS 2005 anymore. It's good for VS 2008. But it's not all of that shiny new concept feature.

Let's talk LINQ!

LINQ is one of many ways of solving the problem of "impedance mismatch of relational data and objects", which has been around for years. More about this, see here, and here ("The Vietnam of computer science"), and the response of it on CodeProject.

Although there are many ORM product that's been trying to solve this and in some degrees they solved it, none of them offer the deep integration of query language inside the general language programming such as C# and VB.NET. As a side effect, many has asked, "Is ORM tools dead?" But none of this make enough sense for me. LINQ is not meant to kill other ORM tools! Believe it or not, comparing to some aspects of IdeaBlade DevForce and Wilson's ORM, LINQ is still a long way to go, and LINQ shouldn't be used alone.

Some sample uses of LINQ

This is the easiest sample of LINQ, try to do SELECT query. I'm now querying the available (collection of) running processes in my computer (yes, LINQ can query collections).

First, make a Console project using C# or VB.NET before running this sample.

This is the code example (taken from Anders Hejlsberg's video):

In C#:

    class Program
{
static void Main(string[] args)
{
Console.WriteLine("LINQ Sample");
Console.WriteLine("listing of my running processes");
var runproc1 = from Process p in Process.GetProcesses()
select new { p.Id, p.WorkingSet64 };
foreach (var proc in runproc1)
{
Console.WriteLine("{0} size={1}", proc.Id, proc.WorkingSet64);
}
Console.ReadLine();
}
}

In VB.NET:

Module Module1

Sub Main()
Dim query = From p As Process In Process.GetProcesses() _
Select p.Id, p.WorkingSet64
For Each proc In query
Console.WriteLine("{0} size={1}", proc.Id, proc.WorkingSet64)
Next
Console.ReadLine()
End Sub

End
Module

Those two codes above will display current running processes on your machine with the id and working set. You can also display ProcessName if you want to. It's simple, right?


Actually, query variable is of type IEnumerable<T>. This means you can treat query as a collection and it's also queryable.


Now, enough introduction. LINQ is actually consisting of:



  • LINQ to Objects (it's the sample above)
  • LINQ to SQL (DLINQ)
  • LINQ to XML
  • LINQ to DataSet
  • LINQ to Entity (part of the ADO.NET Entity Framework)

Note, that LINQ to SQL only works for SQL Server 2005 and above, but not for others such as Oracle or IBM DB2.


If you're using VS 2008, you can code using DLINQ generated object and have them queryed directly. Later post on more on DLINQ.


But, there'll be more about .NET 3.5! I'll try to bring you more LINQ and the other new goodies in .NET 3.5.


What about .NET 3.0? In future posts I'll also make some flashback to .NET 3.0, where the buzzwords are WPF,WCF,WF, and CardSpace (although sadly enough there are very little examples and resources about CardSpace).


kick it on DotNetKicks.com

Sunday, January 6, 2008

Quick thoughts on .NET 1.x, 2.0, 3.0, and 3.5 (part two)

Remembering .NET 1.x

If you're not a real software geek or just a seasoned IT Professional, you can get more information from Microsoft .NET official site:

http://www.microsoft.com/net/

There, you can begin to delve .NET from outside view of non software developers.

Now, why do I call "Quick thoughts on .NET 1.x" instead of .NET 1.0 and .NET 1.1? Basically, the releases of .NET 1.0 and .NET 1.1 are essentially the same, although the language features from C# and VB.NET perspective, are different. The CLR is also the same between release of 1.0 and 1.1.

.NET 1.1 is basically adding minor new features while also squashing bugs in .NET 1.0.  .NET 1.0 is of course the first release of .NET. Microsoft has long planned .NET Framework long before the release of Visual Studio 2002 (a.k.a VS 7.0). My interest and curiosity about .NET was awakened after I saw an article on BusinessWeek in late 1999. I forgot the exact date, but it had the cover of two Microsoft employees were setting up a .NET logo flag!

It was a huge bet for Microsoft, since it was dubbed as an application platform, and it's somehow could bring confusion to existing Microsoft platform of Win32 API, while facing the fact that web itself was becoming a platform too. XML was also the center of

In 2000, in MSDN Library online or offline version (from MSDN subscription), Microsoft began to provide many articles and preliminary documentation of .NET. The namespaces, class names, were quite changed many times. In July 2001 of MSDN Library (offline) edition, .NET was added as .NET beta documentation. At that time, .NET 1.0 namespace changes was frozen, but class name changes were there, but only small changes.

As always, Microsoft makes gimmicks and beta documentation of their products, but they often got the fact not yet released for public.

But after the introduction of Visual Studio 2002, many things had happened.

VB 6 developers were revolting!

Sadly, on the VB 6 programmer side, it makes some of old VB 6 developers to be left in the cold. VB.NET is a whole new programming concept, although the basic language keywords are remain the same. As a result, there is a VB petition from many die hard VB 6 MVPs and developers, but I assume some of you will ignore this. Let's just say from Robert McLaws perspective, don't be a spoiled brat of being a Microsoft MVP. I believe many of you, including me, are not MVP, but we have a good spirit of software geek, including always and continuous learning and coding, right? But in the end, the choice is ours to make.

As a matter of fact, in my objective opinion, a petition of voicing concerns of many huge bases of VB 6 developers is definitely a good thing, which means that MVP has to be independent from Microsoft.

Okay, we had .NET 2.0 in 2005 back then...

In early 2004, again, Microsoft had begun voicing the next major release of ,NET 1.x, the .NET 2.0. Some of my .NET 2.0 early adopters friends told me that they began toying with .NET 2.0 in late 2003. But in MSDN Library April 2005 edition, Microsoft stated that .NET 2.0 was frozen (in features) and would be released soon.

But what makes me quite disappointed even until now, that offline version of MSDN Library is always only geared toward .NET specific release and Visual Studio specific release, instead of giving enough time to make transition between releases. But sadly, in MSDN Library that is specific for Visual Studio 2008, you still find many old articles of .NET 1.x. What I want is, if it's really geared toward .NET 3.5 and Visual Studio 2008, why do I still have megabytes of .NET 1.x article references? But, you can download MSDN Library for Visual Studio 2008 freely, anyway. Be patient if you have really slow Internet connection, though. Since it's about 2GB in size. If you have a good/decent connection, you can always view online MSDN Library.

.NET 2.0 brought a newer CLR, and although it's backward compatible with .NET 1.1, you should recompile your source in .NET 2.0 if you want to migrate it smoothly. Don't take any risk! Because .NET 2.0 has different CLR and this means different IL (.NET Microsoft Intermediate Language) to handle. That's also a runtime backward problem. For example: don't try to run/debug .NET 2.0 executable program in .NET 1.1 environment. It won't work.

One notable features that brings the new release on both .NET 2.0 and Visual Studio 2005, is the inclusion of Generics. This is one of my reason of deciding which platform and which platform's version have.

And now we still have .NET 2.0 in .NET 3.0 and 3.5!

Because, just like my previous post, .NET 3.5 is basically .NET 3.0 with new features (but not new CLR), and .NET 3.0 is basically .NET 2.0 + WPF + WCF + WF + CardSpace.

.NET 2.0 is the beginning of CLR 2.0. Changes are minimal after releasing 3.0 and 3.5. But what about LINQ in .NET 3.5?

Thursday, January 3, 2008

Quick thoughts on .NET 1.x, 2.0, 3.0 and 3.5 (part one)

Yes, the current version of .NET is .NET 3.5. It contains new features, but the most notable new feature is the release of LINQ, Language INtegrated Query.

 

First, let's talk about CLR in .NET 3.5

 

But before I delve more deep, let's see the fact that there's no new CLR for this release (3.5) since .NET 2.0. Again, Daniel Moth has brought us quite deep explanation about this. But this is quite a relieve, since the incompatibilities of .NET 1.x and .NET 2.0. I remember when I was finishing ASP.NET 1.1 project, my client's web hosting quietly changed their .NET version to 2.0. And then ASPX pages stopped working, since almost all of them displayed errors and exceptions. (I won't share the name of my client's web host, but email or message me in private if you want to).

I'm happy that there's no new CLR at this moment of 3.5. There are (yes, even until now, not were) some irrelevant arguments about whether there's a new CLR or not. If you find news about new LINQ and new CLR, and if there's somebody thinks new that new language keywords == new CLR, you're dead wrong! LINQ and .NET 3.5 don't bring new CLR. These new language keywords and hence, constructs, are not bringing new CLR. These new keywords of LINQ in C# 3.0 and VB 9 are just language features. Your new CLR of 3.5 still run under .NET 2.0, unless you're using newer class libraries of .NET 3.5.

For more information about what is CLR, see this article from TheServerSide and CLR is based on standard-based CLI from ECMA. Here's the official spec of CLI.

Can I have the illustration about this?

Yes.

On many occasions, Microsoft's bloggers often mention red bits, green bits, and some additional features in .NET 3.5. Somasegar, the VP of Dev Division at Microsoft, also discussed what these color bits mean.

Hmm... looks like more and more headache concerning new technologies? Fear not, there are numerous resources of .NET 3.5 for us. From that simple Venn diagram above, it's clear that .NET 3.5 is also .NET 2.0.

So, green bits are what we have now, the .NET 3.5!

Basically, .NET 3.5 in long math equation is:

.NET 3.5 = .NET 2.0 SP1 + .NET 3.0 SP1 + new features

What are the new features, really?

In short, these are:

  • LINQ
  • Lambda Expression in C# 3.0 and VB 9
  • WPF 2D on 3D support
  • Integration of MS Ajax Extension into base .NET 3.5 assembly.
  • Addins API

Unfortunately, there's no single file for .NET 3.5 redistributable runtime to download. Even .NET 3.5 SDK, is not available in its full form, unlike the .NET 3.0 SDK that ships as part of Windows SDK 6.0.

So, there's no standalone .NET 3.0 SDK to download. Another sad thing is, there's no standalone .NET 3.5 SDK to download at this time. .NET 3.5 SDK will be included in release of Windows 2008 SDK, which is about 1.3 GB in size!

Try to download Windows 6.0 SDK? It's whopping 1.2GB in size! Unless you have broadband connection at least DSL, you should wait for VS 2008 Standard Edition or Professional Edition to be sold worldwide, or you can get them if you're MSDN Premium subscriber.

More on LINQ and other new features? Stay tuned!