Aug 1 2007

Automatic Proeprties

Category: C# 3.0Bil@l @ 08:06

In every 3-tier application we develop, there is always a need for model objects, which are nothing but classes we use to pass between DataAccess, Business, and UI layers. These classes contain only
simple properties that represent the columns of a Data Table that are retrieved from the database. As you can see, those objects need not any validation logic, dummy proeprties! We can use code
generation tools like CodeSmith, or even develop ower own tools too. But with C# 3.0, no need for any code generation tools anymore!!

A new feature of C# 3.0 is the Automatic Properties, you can write model classes in a more compact way and with less code! And the rest is left to the C# 3.0 compiler!

An example makes things clear:

  public class Customer {
  public int ID {get; set;}
  public string Name {get; set;}
  public Address Address {get; set;}

 public class Address {
         public string City {get; set;}
         public string Building {get; set;}
         public string Phone {get; set;}

As you can see I have written a class with minimal code. What happens at compile time is that, the C# 3.0 compiler will generate a full class including private fields and this way you can use the
Customer/Address classes are any normal class with one exception, we have written fewer lines of code and the rest was on C# 3.0 compiler that generates the full class for us!

Hope this helps,


Comments are closed