We all know how automatic properties feature of .Net 3.5 left us improving our development time. Although we had the snippet facility to create properties earlier, it is too boring to keep creating private variable and a public property using each variable. Automatic property helps us in those situation. But there is a constraint that we cannot create automatic property as"read only" or "write only" property. Let's see why?
Automatic properties are defined as follows.
public int Width
{
get;
set;
}
It might look simillar to declaring a property in the abstract class in .Net 2.0. The difference between them is just the abstract keyword. Moving on, automatic properties create a private variable internally. It may look like
private int width
public int Width
{
get
{
return width;
}
set
{
width = value;
}
}
this look similar to .Net 2.0 way of creating properties.
Automatic property creates a private variable by itself for its use. What it exposes is only the property which is fair enough for us to work on. But again, why no "readonly" or "writeonly"? If we create a property for readonly purpose, we have to do it as follows
public int Width
{
get;
}
In this case, we dont know the private variable created by the .Net for us as it is created at runtime. So, we cannot set the value of the .Net created variable through our program so that it returns the value when the Width property is referred.
So, the only way is to create a variable by ourselves and use it in our program to return it. That's why readonly and writeonly properties cannot be created automatic. We should create it explicitly as we do it in .Net 2.0 or earlier.
Subscribe to:
Post Comments (Atom)
1 comment:
If you are adamant, there is alternative way of implementing.
Refer code snippet below:
// Read only
public int age
{
get;
private set;
}
// Write only
public String Address
{
private get;
set;
}
Post a Comment