LINQKit: “C# 3.0 In A Nutshell” Extras

The "C# 3.0 in a nutshell" book has some neat free extras that are worth mentioning for those who haven’t already heard of (they have been released for long). Those are like must-have LINQ tools and helpers.

The homepage of LINQKit (the major part of the extras I’m going to cover here) provides great information and short code samples about the components:

  • LINQPad This is a snippet compiler (application to run/try small codes in separation than big VS projects, like this), that’s customized for LINQ queries. You can use the SQL Server Query Analyzer -like application to try your codes on the tables in the DB, and see the resultant output and SQL query. Very useful for learning LINQ and/for for making up complex LINQ Queries

  • PredicateBuilder

    This is a dynamic query library. If you ever tried LLBLGen (one of the best .NET OR mappers), it’s equivalent to PredicateExpression and PredicateFactory stuff. If not, then it’s a dynamic way of creating queries. Sometimes you want to add/remove conditions to/from your query based on runtime decisions, and you can’t do that with the standard query way, so, this library allows you to write code like this:

    var predicate = PredicateBuilder.False<Product>();
    <span class="kwrd">foreach</span> (<span class="kwrd">string</span> keyword <span class="kwrd">in</span> keywords)
        <span class="kwrd">string</span> temp = keyword;
        predicate = predicate.Or(p => p.Description.Contains(temp));

    Of course you could wrap the ".And" and ".Or" parts in an "if" statement based on any check you like, which is the real power here!

  • Improvements / Workarounds

    When you deal with LINQ much enough, you’ll get many limitations (as everything else :D). For example, sometimes you cannot set conditions on related entities (like setting conditions on the "Pruchase"s of a "Customer". Also, you’ll want to do more with the expressions you use, mainly combine two different expressions together, use advanced queries with related entities, doing more stuff asynchronously, etc. The LINQKit has many small extension methods you use in your normal query or your dynamic query to work around that and more.

  • LINQBridge

    If you find that you have to work on some .NET 2.0 project, it doesn’t mean you lose LINQ. LINQBridge allows you to write queries like this one.

    <span class="kwrd">int</span>[] numbers = { 5, 15, 7, 12 };
    var query = numbers
      .Where (n => n > 10)
      .OrderBy (n => n)
      .Select (n => n * 10);

Check out the extras page for more code samples and the library download with demo solution and library source code.

Technorati Tags: C#,LINQ,LINQPad,C# 3.0

The C# Modifier ‘new’

This is ported from my old weblog. Originally published April 07, 2005

There was a question in Microsoft Forums regarding the new modifier in C# and what’s the difference between using it and using the virtual and override modifiers. I wanted to share that here as well.

The new modifier is mainly used for hiding the non virtual methods. Unlike override modifier, it’s used to hide all class members not only methods (i.e. variables and properties). If you create a Base class with a protected, internal or public int for example, and inherit that Base in another class called Child, placing another x in it and try to compile this, the code will compile successfully! However, if you look at the tasks window (assuming that you are using VC#) you’ll see a warning that you should use the new keyword with the second declaration. A simple code should tell you what I mean here:

using System;
namespace ConsoleView
      public class Base
            //The original member
            public int x;
      public class Child:Base
            //This declaration will compile well, but,
            //will generate the following warning :
            //The keyword new is required on 'ConsoleView.Child.x'
            //because it hides inherited member 'ConsoleView.Base.x'
            public int x; 

Anyway, this is not the primary purpose for the modifier. The main purpose comes when you use it to hide a method instead of using override (by the way, to hide a method, you can’t use both override and new. This gives you an error not just a waning).

Using virtual and override modifiers will always be similar to using the new modifier except that when you use virtual and override you can’t call the the Base class except from inside the Child class itself (meaning from the Child class methods only). To make this clearer, if you cast the child as Base and call the virtual method, you’ll still get the overriden version not the vertual (original) one. This happens becasue override totally replaces the Base virtual method. It doesn’t just hide it.

Now, if you leave the original Base method with or without the virtual modifier (it doesn’t matter here), and use the new modifier with the Child version of this method, you’ll be hiding the original method only when Child is treated as a Child (Not casted as Base). If you cast it as Base, and call the same method, you’ll get the original version of the method, not the new one.

If you feel confused, check the following code segment:

using System;
namespace ConsoleView
      //This holds only original versions of the methods
      public class Base
            //This method will be overriden by Child, so, it'll never execute
            public virtual void View()
                  Console.WriteLine("Viewing Base, Original virtual View");
            //This method will be hidden only from inside Child (using 'new' modifier)
            //Note that I could make it virtual too, this wouldn't change anything
            public void ViewNew()
                  Console.WriteLine("Viewing Base, Original OLD ViewNew ;)");
      //this class holds all the edited versions of methods
      public class Child:Base
            //Here I use override to permanently replace the original method
            //Whatever the reference type is,
            //    this'll always be the method executed when you call View()
            public override void View()
                  Console.WriteLine("Viewing Child, override View");
            //this hides the method only if the refernce type is Child or inherited from Child
            //a call from a reference of type Base will execute the OLD method, not thiis one
            public virtual new void ViewNew()
                  Console.WriteLine("Viewing Child, new View");
      /// Used to hold the 'Main' method only!
      /// to show up the result of using each in the Console
      class Implementor
            /// The main entry point for the application.
            /// Used to show up what's the expected result.
            static void Main(string[] args)
                  //This part is very typical
                  //Creating a Child reference, and it referes to (its value is) a child
                  Child myChild=new Child();
                  //Indicating reference and value types in the output
                        ("The reference now is a Child that refers to a child. Typical, ha?!");
                  //Will show up the overriden version
                  //as it has been totally overriden using the override modifier
                  //Shows up the new version,
                  //as the new modifier hid the original version
                  //The difference comes here
                  //The reference is a Base, but it refers to (its value is) a Child
                  Base myBase=(Base)new Child();
                  //Indicating the previous change in the output
                        ("nnThe reference now is a Base, yet it still refers to a child");
                  //Will show the overriden version,
                  //even though the reference is of type Base,
                  //it's been totally overriden, not just hdden
                  //Will show the original version NOT the new one
                  //as the new hides the method in Child only
                  //it doesn't override it totally
                  //Just to halt the screen so that I can read the output

This code should be explainning itself on its own. I just show that when I call the virtual method ‘View()’ using a Child reference or Base refernce, I always get the overriden version, on the other hand, when I call the ‘ViewNew()’ method using a Base reference, I get the original version. I get the “new” version only when I use a Child reference (or reference of any type that is inherited from Child itself).

This should be the output of that program:


A good remark is that a method can be new and virtual at the same time, just in case you wanted to allow others to override your new method, especially if the old method is not a virtual one ;)

If you are seeking the official word from MSDN, Check MSDN LibraryDevelopment Tools and LanguagesVisual Studio .NETVisual Basic and Visual C#ReferenceVisual C# LanguageC# Programmer’s ReferenceC# KeywordsOperator Keywords > new.

Finally, just tell me if this is too much, causes you confusion, or just never helped you by any means!


Technorati Tags: C#,CSharp,OOP