Today I had an interesting discussion with a colleague from another company. We started to talk about C# properties and how useful are in situations when you need to set or get the values of different object characteristics.
Properties are perfect when you work with DTO - Data Transfers Object. For this case you don't need to have any kind of logic inside.
Properties can be defined very simple:
Until now nothing special. But what about cases when the setter needs to be public and getter is required to be private. This situation is not common, but once or two times in life you encounter this case.
I was surprise to find out that he thought that you cannot define geeter private and setter public. Even if this this now common, you can do something like this.
.NET allows us to put any kind of visibility attribute before getter and setter. We have no restriction related to this.
Properties are perfect when you work with DTO - Data Transfers Object. For this case you don't need to have any kind of logic inside.
Properties can be defined very simple:
public class Foo
{
public string Name
{
get;
set;
}
}
Simple, I bet that you already knew this. When we went with discussion deeper, we talk about cases when you need to expose only the getter public and setter needs to be private. This can be useful when the value needs to be set only in ctor (constructor) or internally, during deserialization.public class Foo
{
public string Name
{
public get;
private set;
}
}
Good!Until now nothing special. But what about cases when the setter needs to be public and getter is required to be private. This situation is not common, but once or two times in life you encounter this case.
I was surprise to find out that he thought that you cannot define geeter private and setter public. Even if this this now common, you can do something like this.
public class Foo
{
public string Name
{
private get;
public set;
}
}
.NET allows us to put any kind of visibility attribute before getter and setter. We have no restriction related to this.
Comments
Post a Comment