Getting Started with Adobe After Effects - Part 6: Motion Blur


Upload Image Close it
Select File

Browse by Tags · View All
BRH 9
#DOTNET 8
#DATAACCESS 7
Data Access 5
.NET 2
VS2010 2
dot net 2
DAAB 2
#LINQ 2
LINQ 2

Archive · View All
May 2010 5
April 2010 3
May 2011 1
December 2010 1

Deepak Palkar's Blog

Getting Started with LINQ – Part 2 (Language Enhancements)

May 5 2010 4:42PM by Deepak Palkar   

In my previous post I summarized Microsoft Language Integrated Query (LINQ). Briefly discussed about its components as well as showed some code examples to highlight the sql query type syntax it uses. Please don’t get confused about the title of this post. We sure are going to talk about language enhancements but they are the features of C# 3.0, and not the features of LINQ. But they are the building blocks of the LINQ. In this post I will discuss these features a little further as follows.

  • Object Initializers
  • Collection Initializers
  • Anonymous Types, Implicitly Typed variables (var keyword)
  • Lambda Expressions
  • Partial Methods
  • Extension Methods

Object Initializers
Generally, when we initialize an object we use following different ways.

        //Initialize by passing properties through constructor
        Employee e1 = new Employee(1, "John", "Smith");

        //Initialize with default constructor
        //then set the properties explicitly 
        Employee e2 = new Employee();
        e2.Id = 1;
        e2.FirstName = "John";
        e2.LastName = "Smith";

With Object Initialization you can do the same thing like this. Mind you, this is a single line code but I have deliberately expanded it into multiple lines for the sake of readability. Pay attention to commas inside the curly braces and a semicolon at the end.

        
	//Object Initialization
        Employee e3 = new Employee
                    {
                        Id = 1,
                        FirstName = "John",
                        LastName = "Smith"
                    };

Object initialization allows you to specify the initialization values for publicly accessible members and properties of a class during initialization.

Collection Initializers
Just like Object initialization we can initialize the collections, as long as the collection implements the System.Collections.Generic.ICollection<T> interface. It means that the legacy collections, which are in System.Collection namespace, can not be initialized with collection initialization. Like Object Initializers, the Collection Initializers allow you to create a collection and initialize it with a series of objects in a single statement. Here's how the collection initializers can be used.

	//Collection initialization, old way!
        List<string> names2 = new List<string>();
        names2.Add("John");
        names2.Add("Jenny");
        names2.Add("Thomas");
        names2.Add("Krishna");
        names2.Add("Jason");

        //Collection Initializer for value types
        List<int> names = new List<int>
        {
            23, 35, 63, 6, 74
        };

        //Collection Initializer for reference types
        List<employee> employees = new List<employee>
        {
            new Employee { Id = 1, FirstName = "John", LastName = "Smith"},
            new Employee { Id = 2, FirstName = "Jenny", LastName = "Banks"},
            new Employee { Id = 3, FirstName = "Thomas", LastName = "Smith"},
            new Employee { Id = 4, FirstName = "Krisha", LastName = "Davis"},
            new Employee { Id = 5, FirstName = "Jason", LastName = "Kimber"}
        };

Anonymous Types, Implicitly Typed variables (var keyword)

select employee.FirstName, employee.LastName, contact.City
From employee, contact
where employee.Id = contact.Id

In above query, we are using two different tables and returning a totally new structure/resultset. There is no such table which has a FirstName, LastName and City columns in it, but the database engine allows us to create that structure on the fly. LINQ has the "Query" word in its name itself, so of course it's definitely trying to mimic the SQL Query syntax. But at the same time, LINQ is also obsessed with the strongly typed objects because generics are one of the strongest building blocks in LINQ. So if we try to do this in LINQ, we should have two classes called Employee and Contact, that's for sure. Now how will we make up for the resultset from LINQ. We can create a new Class which has these three properties in it, FirstName, LastName and City. But we can't go creating classes for each and every resultset we want to return through LINQ queries, do we? Here comes the Anonymous Types for the rescue.

	
	var results = from employee in employees
                          join contact in contacts
                          on employee.Id equals contact.Id
                          select new 
                          { employee.FirstName, employee.LastName, contact.City };

Notice, the part at “select new”, it’s not using any class name there to initialize, but it’s there and it’s anonymous. An anonymous type has no name and is generated by the compiler based on the initialization of the object being instantiated. Since the class has no type name, any variable assigned to an object of an anonymous type must have some way to declare it. That is the purpose of the var keyword. It infers the the type of the object based on the data type with which it has been intialized. Anonymous types allow new class data types to be created on the fly.

Lambda Expressions
Lambda expressions are used in the method-based syntax of LINQ. Lambda expressions use lambda operator =>, which reads as “goes to”. The left side of the lambda operator specifies the input parameter (if any)  and the right side holds the expression or statement block. Lambda expression is actually an anonymous function that can contain expressions and statements.

	
	//Expressions
	//(input parameters) => expression
	
	(x, y) => x == y

	//You can also specify the types explicitly
	(int x, string s) => s.Length > x

	//Statements
	//(input parameters) => {statement; }

	(x, y) => 
	{
		if (x > y)
			return (x)
		else
			return (y);
	}
	
	
Let's write the same LINQ query we used in Anonymous Types, Implicitly Typed variables, using method-based syntax.
	
	var results = employees.Join
			(contacts,
			employee => employee.Id,
			contact => contact.Id,
			(employee, contact) => new 
			{
				employee.FirstName, employee.LastName, contact.City 
			});

Partial Methods
Partial methods are lightweight event-handling mechanism. With partial methods you can create hooks in your code that can be implemented by other developers or by yourself later on. Partial methods can only exist in partial classes. Partial methods are methods where the prototype or definition of the method is not provided in the same declaration of the partial class. They may never be implemented by anyone, in that case, no IL code will be emitted by the compiler for the declaration of the method, the call to the method, or the evaluation of the arguments passed to the method. If is as if the method never existed.

	public partial class Contact
	{
		partial void BeforePropertyChanged(string Propertyname);
		partial void AfterPropertyChanged(string Propertyname);
		
		private string _name;
		public string Name
		{
			get { return _name;
			set { 
				BeforePropertyChanged("Name");
				_name = value;
				AfterPropertyChanged("Name");
			    }
		}

		private string _address;
		public string Address
		{
			get { return _address;
			set { 
				BeforePropertyChanged("Address");
				_address = value;
				AfterPropertyChanged("Address");
			    }
		}

	}

	//In a Different File or project
	public partial class Contact
	{

		partial void AfterPropertyChanged(string PropertyName)
		{
			Console.WriteLine(PropertyName + " Property is changed.");
		}

	}

In first declaration of the Contact class, first two lines are the partial method definitions. We call those methods from the property setters, passing the name of the property for each "event". In second declaration of the Contact class, I am implementing only AfterPropertyChanged partial method and leaving out the implementation of BeforePropertyChanged partial method. In this case, compiler will only emit the IL code for AfterPropertyChanged method as it has been implemented.

Partial methods are used in LINQ to SQL entity classes by the entity class generator tools, to make the generated entity classes more usable, somewhat the same way I have demonstrated above. Here are the rules for partial methods.

  • Partial methods must be defined and implemented in partial classes
  • partial modifier must be used
  • Partial methods are private but they must not specify the private modifier and hence they can not be virtual
  • They must return void
  • They may be unimplemented
  • They may be static
  • They may have arguments
  • They can have ref but not the out parameters

Extension Methods
Extension methods are a technique  to enhance an existing class by adding new method to it without ever changing the existing code of that class. Imagine, you want to convert a string like “3.1415926535” to double, which you can of course easily do it using Double.Parse() or Double.TryParse() methods. But wouldn’t it be great if the String class itself had a method ToDouble()!? Well you imagined and now you can do it for real using the extension methods.

	//Declaration of the Extension Method
	public static class StringConversions
	{
		public static double ToDouble(this string s) 
		{
			return Double.Parse(s);
		}
	}

	//Using Extension Method
	string number = "3.1415926535";
	double pi = number.ToDouble();
Extension methods must be created in a static class and method itself has to be static too. As you see the only tricky thing here we see is the this keyword. It tells the compiler that we want to add this extension method to String type. The best example how LINQ uses the extension methods is, if you remove the "using System.Linq" from top of your class, you'll see a lot many methods have disappeared which had a <> with them when you type "dot" after of instance say List. LINQ uses extension methods thoroughly with its method-based syntax. Normal object instance methods take precedence over extension methods when their signature matures the calling signature. Extension methods is a great concept which allows you to extend a class which might even be sealed, like we extended the String class above.

Conclusion:
These features as I mentioned earlier, are the building blocks of LINQ but they are not there just for LINQ. They can be used by themselves too. That’s why they are called the language enhancements and not LINQ features.

Happy Coding!!

Tags: BRH, LINQ, #DATAACCESS, #DOTNET, #LINQ,


Deepak Palkar
177 · 1% · 269
0
Liked
 
0
Lifesaver
 
0
Refreshed
 
0
Learned
 
0
Incorrect



Submit

Your Comment


Sign Up or Login to post a comment.

    Copyright © Rivera Informatic Private Ltd Contact us      Privacy Policy      Terms of use      Report Abuse      Advertising      [ZULU1097]