Using Automatic Properties in LINQ with C#


Server Intellect


Using Automatic Properties in LINQ with C#

This tutorial was created with Microsoft Visual Studio .NET 2008, which comes with LINQ built-in. If you are using Visual Studio .NET 2005, you can still use LINQ by downloading Microsoft's LINQ Community Technology Preview release from here.

In this tutorial, we will look at how we can use LINQ to create quick classes, and allow LINQ to generate the Properties for us. Traditionally, we'd spend a lot of time coding the classes to represent our database data, but now, we can use LINQ to help us in creating these classes - and also with instantiating as well.

Let's start by creating a new web application in Visual Studio. We will create a new class - goto the Solution Explorer, right-click on the Project and choose to Add ASP.NET Folder > App_Code. Then right-click on the new App_Code folder and choose to Add New Item.. Class. Give it a descriptive name - for this example, we choose People.cs

Now we should have something that looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for People
/// </summary>
public class People
{
public People()
{
//
// TODO: Add constructor logic here
//
}
}

Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.

We can get rid of the constructor, as we will not be using that to create a new instance. To use Automatic Properties, we do not add logic to the Getters and Setters, we want the C# compiler to do this for us. NOTE: it is not possible to create Read-Only Automatic Properties. A Normal Property that we're used to creating may look something like this:

public Int32 ID
{
get
{
return _ID;
}
set
{
_ID = value;
}
}
private Int32 _ID = 0;

Believe it or not, we can minimize this down into one line of code, using Automatic Properties. This will look something like this:

public Int32 ID { get; set; }

We used over 10 web hosting companies before we found Server Intellect. Their dedicated servers and add-ons were setup swiftly, in less than 24 hours. We were able to confirm our order over the phone. They respond to our inquiries within an hour. Server Intellect's customer support and assistance are the best we've ever experienced.

We can do this for all of our Properties:

public Int32 ID { get; set; }

public String Name { get; set; }

public String City { get; set; }

public Int16 Age { get; set; }

Now to create a new instance of this class, we can do it the old way - or the new LINQ way. The old way will look something like this:

People person1 = new People();
person1.ID = 1;
person1.Name = "Fred daRedd";
person1.City = "Fort Lauderdale";
person1.Age = 34;

We can condense this down to one line using LINQ like so:

People person2 = new People {ID = 2, Name = "Alanis Morieuvue", City = "Bratislav", Age = 24};

We chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.

Finally, to demonstrate our new class instances, we can output the properties to our ASPX page using a Literal control:

lit_Display.Text = "<strong>Person1:</strong> " + person1.Name + ", " + person1.City + " (" + person1.Age.ToString() + ")<br />";
lit_Display.Text += "<strong>Person2:</strong> " + person2.Name + ", " + person2.City + " (" + person2.Age.ToString() + ")<br />";

You can see how easy LINQ and the new features of the C# language make it for us to not only create our own classes, but to instantiate and use them as well.
Our ASPX page has just the one Literal control to output the properties:

<form id="form1" runat="server">
<asp:Literal ID="lit_Display" runat="server" />
</form>

The output to the webpage will look like this:

Person1: Fred daRedd, Fort Lauderdale (34)
Person2: Alanis Morieuvue, Bratislav (24)

Finally, our entire code-behind looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
People person1 = new People();
person1.ID = 1;
person1.Name = "Fred daRedd";
person1.City = "Fort Lauderdale";
person1.Age = 34;

People person2 = new People {ID = 2, Name = "Alanis Morieuvue", City = "Bratislav", Age = 24};

lit_Display.Text = "<strong>Person1:</strong> " + person1.Name + ", " + person1.City + " (" + person1.Age.ToString() + ")<br />";
lit_Display.Text += "<strong>Person2:</strong> " + person2.Name + ", " + person2.City + " (" + person2.Age.ToString() + ")<br />";
}
}

Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!
 


Comments
multiplayer poker said:

I like your syntax better :) With the empty get; set; it feels too much like an interface. I'm sure whatever we end up with will become second nature within a couple days anyway. It's nice of them to include such features that save me from typing a couple extra of lines of code.

Posted 07/03/2009 at 3:15 AM
DVEANG said:

THANK YOU YOUR WEBSITE IS OSSAM I LIKE TYO REFER IT

Posted 10/30/2009 at 7:06 AM
Hanumantha Rao said:

Nice article.

Posted 12/13/2009 at 11:06 PM
Shankar said:

This is a very nice and helpful article

Posted 02/15/2010 at 3:35 AM
diabetes cure said:

With C# 3.0 a new feature called "automatic properties" is now available. When you use the "prop" code snippet in Visual Studio 2008 you'll see that empty get and set blocks are added and that no associated field is added into the code. The compiler will automatically generate the backing field at compile time if it finds empty get or set blocks saving you the work. You can still add get and set blocks that have additional filtering logic in them as well although you'll have to type all of that yourself of course.

Posted 04/05/2010 at 9:12 PM
Essay said:

Here light is shed on how to use Automatic Properties in LINQ with C#. First of all he points that he is using .NET 2008 in this tutorial and that if we are using .NET 2005 we still can use LINQ by downloading from internet. Here information regarding using LINQ to create quick classes and allowing LINQ to generate properties is provided. He starts by creating a new web application in studio. Then he clearly presents the programming part. I think this is a wonderful blog with special emphasis on clarity. Here the author beautifully conveys his idea by using simple English.

Posted 05/04/2010 at 8:59 PM
Grow taller said:

The compiler will automatically generate the backing field at compile time if it finds empty get or set blocks saving you the work. You can still add get and set blocks that have additional filtering logic in them as well although you'll have to type all of that yourself of course.

Posted 05/13/2010 at 5:48 AM
migliori Jackpot dei casinò in rete said:

casino bacara said:

There's no doubt that LINQ is one of the headline features of Visual Studio Orcas. I've been trying out some LINQ queries; it's a very interesting new area with massive potential. It seems though that most books and articles available at the moment are C# based, so I thought I'd blog my journey through the Land of LINQ in case any other VB DotNetters might find it useful now or in the future.

Posted 05/19/2010 at 2:16 AM
Luxury Villas said:

Well....To use Automatic Properties, we do not add logic to the Getters and Setters, we want the C# compiler to do this for us. NOTE: it is not possible to create Read-Only Automatic Properties.Thanks

Posted 07/07/2010 at 10:15 AM
junk yards said:

We're working with Visual Web Developer in Computer Science class at the moment, and we're supposed to take pieces of VB code and make our own project in C#. I understand that this here is taking a list of font names and filling a ListBox with them, but I have no idea how to go about doing that in C#. If anyone could help out, it would be appreciated.

If Not IsPostBack Then

Dim q=From f In System.Drawing.FontFamily.Families _

Select f.Name

ListBox1.DataSource = q

ListBox1.DataBind()

End If

Posted 07/28/2010 at 9:16 PM
DJ Equipment said:

The compiler will automatically generate the backing field at compile time if it finds empty get or set blocks saving you the work. You can still add get and set blocks that have additional filtering logic in them as well although you'll have to type all of that yourself of course.

Posted 07/31/2010 at 11:09 AM
Flyer Design said:

I wanted to thank you for this excellent read. I definitely loved every little bit of it. I have you bookmarked your site to check out the latest stuff you post.

Posted 07/31/2010 at 2:23 PM
Business Gifts said:

Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative.

Posted 07/31/2010 at 2:23 PM
SEO Consultant said:

Recently, I didn’t give so much thought to writing comments on blog entries and have left comments even less. Checking out your informative page, will probably encourage me to do this more regularly.

Posted 07/31/2010 at 2:24 PM
Wedding Planner said:

Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative.

Posted 08/03/2010 at 4:28 AM
bridal design said:

i like this site.. have a lot of information.... these type of sites always magnetize me to post comment...

<a href="http://www.thebridaldesign.com">bridal design</a>

<a href="http://www.thebridaldesign.com">bridal dresses</a>

<a href="http://www.thebridaldesign.com">bridal botique</a>

Posted 08/07/2010 at 10:28 AM
LED Pods said:

The compiler will automatically generate the backing field at compile time if it finds empty get or set blocks saving you the work. You can still add get and set blocks that have additional filtering logic in them as well although you'll have to type all of that yourself of course.

Posted 08/08/2010 at 4:06 PM
Keychains said:

Its always good to get useful information like you share for blog posting. thanks for the info.

Posted 08/13/2010 at 12:04 AM
round stickers said:

Such a very valuable information. Thanks for this excellent read.

Posted 08/13/2010 at 12:29 AM
seo Newcastle upon tyne said:

I would like to thank you for the efforts you have made in composing this article. thanks for sharing the great information.

Posted 08/13/2010 at 2:48 AM
Cotton Yarn said:

Very knowledgeable reading. This is such a great resource that you are providing.

Posted 08/13/2010 at 2:59 AM
Short Death Poems said:

Useful information shared..I am very pleased to study this article..many thanks for giving us nice information.

Posted 08/13/2010 at 6:35 AM
online roulette said:

I am also having problems with NavigationService.Navigate, to a page with javascript parent I also had problem with another bug..

Posted 08/20/2010 at 7:10 AM
Cheap San Francisco Giants Tickets said:

You can still add get and set blocks that have additional filtering logic in them as well although you'll have to type all of that yourself of course.

Posted 08/25/2010 at 7:10 AM
Cheap San Francisco Giants Tickets said:

You can still add get and set blocks that have additional filtering logic in them as well although you'll have to type all of that yourself of course.

Posted 08/25/2010 at 7:11 AM
coach outlet said:

coach outlet

Posted 08/26/2010 at 1:58 PM
louis vuitton bags said:

louis vuitton bags

Posted 08/26/2010 at 1:59 PM
xiaopohai said:
Posted 08/26/2010 at 9:18 PM
organisme de credit said:

Don’t you know that you are really talented thesis topics creator and the dissertation writing services won’t compare with your writing skillfulness. If you keep on doing the things like this, some people would buy thesis close to this topic not at custom thesis writing services, but purchase from you also.

Posted 08/28/2010 at 1:42 AM
Arvind Kumar said:

I hear and I forget, I see and I remember. I do and I understand...

Hey!

So don't forget to visit - www.faqpanel.com ,

See it and remember it, Do read FAQs on www.faqpanel.com

and understand how to conquer the interview.

Posted 08/28/2010 at 9:24 AM
adjustable bed frame said:

Great minimalist designs. I'm a firm believer in the k.i.s.s. design method. After all, most of the biggest sites on the web use minimalistic designs, like Google, eBay, Amazon, etc. As long as it's a good user interface, minimalist design is a great choice.

Posted 08/29/2010 at 8:19 PM

Leave a Comment