Tag Archives: atic Properties in c# .net 3.5

C# 3.0 Language Features

While Talking about .Net Framework, there are lots of many new things in every version, but I normally keep an eye on mostly used features from the perspective of re usability and easy of Code.

While Exploring, I crossed through some really usable features of .Net 3.0 & 3.5, and for the discussion here I would be covering Automatic Properties, Object Initiation, Extraction Methods, and Automatic Type Casting.

Automatic Properties

Normally, In every sort of project, specifically in every class most the time is eaten by the writing the class members and their setter and getter (properties or Indexers). Although, many third party tools like Visual Assist come up with the power of .Net Extensibility ( I will be writing some useful tips about it Soon), and easy the developer by provider Intellisense to a greater extend, but what If I tell you something built in .Net framework without spending any extra money for any third party Add In. Following is one of my Code Snip that I will use to explain the power and re usability of Automatic Properties.
I’m Omitting any required using statements to make it simpler and shorter.

namespace MyBlogApplication
{
public class PersonClass
{
//Person Class’s Properties
private String _name;
public System.String Name
{
get { return _name; }
set { _name = value; }
}

private String _addess;
public System.String Addess
{
get { return _addess; }
set { _addess = value; }
}

private String _personId;
public System.String PersonId
{
get { return _personId; }
set { _personId = value; }
}
}
}

Although the above code may be generated using the Reflector tools of .net, but it still requires me to write Class members and then reflect them as Public Properties, and of course it requires more lines of code then the one I wrote in .Net c# 3.5 as below

namespace MyBlogApplication
{
public class PersonClass
{
//Person Class’s Properties
public String Name { get; set; }
public String _addess { get; set; }
public String _personId { get; set; }
}
}

What i did just wrote “prop” (this is also available in .net 2.0), and press tab twice, so what I came with is the above snip, now what I need to do is just to give name to my property, and compiler will automatically generate the data member and deals with adding and retrieving from memory.

It’s not a rocket science, but imagine if you have more than 20 properties per class and for each one you have to create and manipulate data members, it’s a hell of coding job, but the above technique reduces and manages you code with beauty.

In the above code, you may put your properties as Read-Only Or Write-Only as follows

//Person Class’s Properties
public int Name { get; set; }
public int _addess { private get; set; } //Write-Only
public int _personId { get; } //Read-Only

Happy Coding with .Net 3.5 🙂

Advertisements