Up to now we were writing following code to create single property.
public class PropertyTest
{
private string _strTest;
public string strTest
{
get { return _strTest; }
set { _strTest = value; }
}
}
Now look at the automatic properties bellow.
public class PropertyTest
{
public string strTest { get; set; }
}
Only single line of code!!!
We can even restrict the get and set property, like we need set property to be private and get property to be public; yes we can do that too.
public class PropertyTest
{
public string strTest { get; private set; }
}
Although its time saver there is few limitation for this, lets list out those limitations.
- Automatically implemented properties must define both get and set accessors, if not have to make them abstract.
//Gives you error
public class PropertyTest
{
public string strTest { get; }
}
//Works fine
abstract public class PropertyTest
{
abstract public string strTest { get; }
} - You can't initialize them in declaration, although you can do it into Constructor
public class PropertyTest
{
public string strTest { get; set; }
public PropertyTest()
{
strTest = "Test String";
}
}
No comments:
Post a Comment