Is it possible to customize access modifiers behaviour? - c#

I have a winform application made up of two assemblies : a business layer and a front-end layer. Each usercontrol (front-end layer) relates to a class of the business layer, i.e. CustomerUserControl uses the Customer class.
Editable properties, i.e. Customer.Name, have public setters so that their values can be modified through front-end controls.
My question is : is it possible to change the setter accessibility of a property to make it more or less restrictive only for specific classes. In my example, the Customer.Name setter would be internal, that is not accessible by front-end controls but accessible for its corresponding control CustomerUserControl. Or else, the setter would be public but not accessible to controls other than CustomerUserControl.
Is it possible to achieve such customized access rights ?

I would use the internal modifier for the setter. This makes it only accessible inside the assembly. If the CustomerUserControl is in another assembly then you can use the InternalsVisibleToAttribute
[assembly: InternalsVisibleTo("assembly name")]
EDIT: You are right. Here is another possibility:
Declare an interface that would be implemented by controls that are allowed to set names:
public interface ICustomerNameProvider
{
string CustomerName { get; }
}
In Customer add a method:
public void SetName(ICustomerNameProvider customerNameProvider)
{
this.Name = customerNameProvider.CustomerName;
}
The CustomerUserControl would call it like this:
cust.SetName(this);
Of cause this is not absolutely fool proof, but accidentally passing the wrong control would become impossible.

As far as I know, there's no way to apply what you're asking for directly to a property setter, since it doesn't know where the call initiated from. However, you could cobble something together using mutator methods:
public class Customer
{
...
public string Name
{
get;
private set;
}
public void SetName(string callingControlName, string newName)
{
// you'd use TypeOf the same way to pass in callingControlName
if(TypeOf(this).Name + "UserControl" == callingControlName)
this.Name = newName;
}
...
}
Note that this is ridiculously tightly coupled and poor design practice, but it ought to do what you want, provided you strictly adhere to the naming conventions outlined in the question (Customer matches 1:1 with CustomerUserControl). As an aside, I didn't just statically compare callingControlName to "CustomerUserControl" in order to gain a slight improvement in maintainability, in case you wanted to do something like rename the CustomerUserControl class. Also important to note is the fact that this is easily defeasible by calling Customer.SetName("CustomerUserControl","badName"). Hopefully you aren't exposing this to coders who would do things like that, but it is entirely possible.
The real issue here is that your business layer shouldn't be dependent on your presentation layer. Why would you need to restrict set access to a specific UserControl? If you have a genuine need (and I can't think of one) that a business property's set only be accessible from a certain UI class, then some significant redesigning of your application is called for.

You can limit the scope of get or set accessors like this:
//private set accessor - this is what you're looking for
public int SomeProperty { get; private set; }
//private get accessor
public int SomeOtherProperty { private get; set; }

Related

How can I fill my rich model from repository when I am no using ORM?

I am trying to develop my application using the DDD approach and I should set all of my properties private. I need to use Aerospike as my database and there is no ORM to fill my properties magically like EntityFramework with a private default constructor.
Now, How can I fill this reach model without exposing a full property constructor that can be accessible everywhere and can breach the rule of encapsulation business domain rules?
making all properties protected and creating an internal inherited class inside the repository namespace that can act as a proxy object to fill property can be a solution But I have no idea about the best practice and acceptable design.
I'm not familiar with Aerospike, but here are my thoughts. First, EF is able to set private properties because it uses reflection to do so. And it needs a parameterless constructor for this. So you could do it the same way: create an object and set properties via reflection.
Or, as others pointed out in the comments, you will anyway need methods to set your private properties, so just use them to instantiate your model. You use private setters and methods in order to ensure that the state of your DDD object is valid and do some internal checks, e.g.:
public class Whatever {
private int age;
public int Age { get; private set; }
public void UpdateAge(int a) {
if (a > 0) {
this.age = a;
}
throw new MyException();
}
}
So just use UpdateAge() and the like. On the other hand it's not necessary to run extra validations if you are instantiating from a database, because all the data in the DB is valid. You could introduce some private variable, like needsValidation, and set it to false in case you are instantiating from the DB via e.g. an internal constructor. Whether it's really worth the effort depends on your use case.

Regarding simple inheritance in C#

I have a question regarding simple inheritance in C#.
Here is the code:
class Mammal
{
int age { get; set; }
public Mammal(int age)
{
this.age = age;
}
}
class Dog : Mammal
{
string breed { get; set; }
public Dog(int age, string breed)
: base(age)
{
this.breed = breed;
}
}
class Program
{
static void Main(string[] args)
{
Dog joe = new Dog(8, "Labrador");
Console.WriteLine("Joe is {0} years old dog of breed {1}", joe.age, joe.breed); // gives error
}
}
This gives error since it cannot access the age and breed parameters. So I make age and breed public in Mammal and Dog class respectively. This makes the program to run fine.
But my question is shouldn't ideally the parameters be made private or non-public and only accessed through public methods? If that's the case, then how can I access the non-public parameters in Program class?
Thanks
Automatic properties are essentially methods (they are compiled to get_ and set_ methods). By marking them public, they will be as you have described, which is fine.
You only need hide the information that an outsider shouldn't have access to. Your use case shows that an outside caller must have access to these properties, so marking them public is fine.
If you don't want an outside caller to set the value, then you can mark that particular accessor as private or protected.. whilst leaving the get accessor public:
public int Age { get; private set; }
Also, uppercase the first letter in properties.
In your code, age and breed are properties. You can control access to the get and set methods separately by writing public get; private set;. That would achieve what you want!
Additionally, consider whether it makes sense in your program to change the age and the breed of an object after it's constructed. If not, you can make them public readonly fields.
Having not provided an access modifier it uses it's default access. However, you're correct in most cases with your logic. You should hide as much as possible. So in reality I, depending on the situation, might provide public getters and private setters - or not. The point to get would be that you're free to do what you like as long as it delivers the correct results.
What you have here, in C#, is the creation of a variable that will always only be accessed via its getters and setters (implicitly of course) because that really is the best, although not so often implemented, practice.
So here:
[access] [type] [name] { [access]get; [access]set; }
we're able to control the access to the parameter but the parameter itself is seen. You could also, obviously because you've done it, make certain fields private that need not be seen, which is the not so implemented way. Often, variables take on some form of validation, no matter the access, so having private parameters like above is advantageous for you to use because the verification can be housed in the setters and allows for simpler syntax with MyClass.Something = somethingElse; or System.Console.Write(MyClass.Something);.
The answer to how can I access the non-public parameters in Program class is that you it can't (without doing reflection), because you can control what member variables, properties and methods are exposed to your derived classes and instantiated classes.
Data encapsulation is a good thing and you should use it to reduce the risk of calling code being able to modify data in your class that they should not have access to.
private will never be available outside the class, you need to make it public when you want to be accessible by all or protected when you want your property/variable/method to be accessible only in inheriting classes.

readonly class design when a non-readonly class is already in place

I have a class that upon construction, loads it's info from a database. The info is all modifiable, and then the developer can call Save() on it to make it Save that information back to the database.
I am also creating a class that will load from the database, but won't allow any updates to it. (a read only version.) My question is, should I make a separate class and inherit, or should I just update the existing object to take a readonly parameter in the constructor, or should I make a separate class entirely?
The existing class is already used in many places in the code.
Thanks.
Update:
Firstly, there's a lot of great answers here. It would be hard to accept just one. Thanks everyone.
The main problems it seems are:
Meeting expectations based on class names and inheritance structures.
Preventing unnecessary duplicate code
There seems to be a big difference between Readable and ReadOnly. A Readonly class should probably not be inherited. But a Readable class suggests that it might also gain writeability at some point.
So after much thought, here's what I'm thinking:
public class PersonTestClass
{
public static void Test()
{
ModifiablePerson mp = new ModifiablePerson();
mp.SetName("value");
ReadOnlyPerson rop = new ReadOnlyPerson();
rop.GetName();
//ReadOnlyPerson ropFmp = (ReadOnlyPerson)mp; // not allowed.
ReadOnlyPerson ropFmp = (ReadOnlyPerson)(ReadablePerson)mp;
// above is allowed at compile time (bad), not at runtime (good).
ReadablePerson rp = mp;
}
}
public class ReadablePerson
{
protected string name;
public string GetName()
{
return name;
}
}
public sealed class ReadOnlyPerson : ReadablePerson
{
}
public class ModifiablePerson : ReadablePerson
{
public void SetName(string value)
{
name = value;
}
}
Unfortunately, I don't yet know how to do this with properties (see StriplingWarrior's answer for this done with properties), but I have a feeling it will involve the protected keyword and asymmetric property access modifiers.
Also, fortunately for me, the data that is loaded from the database does not have to be turned into reference objects, rather they are simple types. This means I don't really have to worry about people modifying the members of the ReadOnlyPerson object.
Update 2:
Note, as StriplingWarrior has suggested, downcasting can lead to problems, but this is generally true as casting a Monkey to and Animal back down to a Dog can be bad. However, it seems that even though the casting is allowed at compile time, it is not actually allowed at runtime.
A wrapper class may also do the trick, but I like this better because it avoids the problem of having to deep copy the passed in object / allow the passed in object to be modified thus modifying the wrapper class.
The Liskov Substitution Principle says that you shouldn't make your read-only class inherit from your read-write class, because consuming classes would have to be aware that they can't call the Save method on it without getting an exception.
Making the writable class extend the readable class would make more sense to me, as long as there is nothing on the readable class that indicates its object can never be persisted. For example, I wouldn't call the base class a ReadOnly[Whatever], because if you have a method that takes a ReadOnlyPerson as an argument, that method would be justified in assuming that it would be impossible for anything they do to that object to have any impact on the database, which is not necessarily true if the actual instance is a WriteablePerson.
Update
I was originally assuming that in your read-only class you only wanted to prevent people calling the Save method. Based on what I'm seeing in your answer-response to your question (which should actually be an update on your question, by the way), here's a pattern you might want to follow:
public abstract class ReadablePerson
{
public ReadablePerson(string name)
{
Name = name;
}
public string Name { get; protected set; }
}
public sealed class ReadOnlyPerson : ReadablePerson
{
public ReadOnlyPerson(string name) : base(name)
{
}
}
public sealed class ModifiablePerson : ReadablePerson
{
public ModifiablePerson(string name) : base(name)
{
}
public new string Name {
get {return base.Name;}
set {base.Name = value; }
}
}
This ensures that a truly ReadOnlyPerson cannot simply be cast as a ModifiablePerson and modified. If you're willing to trust that developers won't try to down-cast arguments in this way, though, I prefer the interface-based approach in Steve and Olivier's answers.
Another option would be to make your ReadOnlyPerson just be a wrapper class for a Person object. This would necessitate more boilerplate code, but it comes in handy when you can't change the base class.
One last point, since you enjoyed learning about the Liskov Substitution Principle: By having the Person class be responsible for loading itself out of the database, you are breaking the Single-Responsibility Principle. Ideally, your Person class would have properties to represent the data that comprises a "Person," and there would be a different class (maybe a PersonRepository) that's responsible for producing a Person from the database or saving a Person to the database.
Update 2
Responding to your comments:
While you can technically answer your own question, StackOverflow is largely about getting answers from other people. That's why it won't let you accept your own answer until a certain grace period has passed. You are encouraged to refine your question and respond to comments and answers until someone has come up with an adequate solution to your initial question.
I made the ReadablePerson class abstract because it seemed like you'd only ever want to create a person that is read-only or one that is writeable. Even though both of the child classes could be considered to be a ReadablePerson, what would be the point of creating a new ReadablePerson() when you could just as easily create a new ReadOnlyPerson()? Making the class abstract requires the user to choose one of the two child classes when instantiating them.
A PersonRepository would sort of be like a factory, but the word "repository" indicates that you're actually pulling the person's information from some data source, rather than creating the person out of thin air.
In my mind, the Person class would just be a POCO, with no logic in it: just properties. The repository would be responsible for building the Person object. Rather than saying:
// This is what I think you had in mind originally
var p = new Person(personId);
... and allowing the Person object to go to the database to populate its various properties, you would say:
// This is a better separation of concerns
var p = _personRepository.GetById(personId);
The PersonRepository would then get the appropriate information out of the database and construct the Person with that data.
If you wanted to call a method that has no reason to change the person, you could protect that person from changes by converting it to a Readonly wrapper (following the pattern that the .NET libraries follow with the ReadonlyCollection<T> class). On the other hand, methods that require a writeable object could be given the Person directly:
var person = _personRepository.GetById(personId);
// Prevent GetVoteCount from changing any of the person's information
int currentVoteCount = GetVoteCount(person.AsReadOnly());
// This is allowed to modify the person. If it does, save the changes.
if(UpdatePersonDataFromLdap(person))
{
_personRepository.Save(person);
}
The benefit of using interfaces is that you're not forcing a specific class hierarchy. This will give you better flexibility in the future. For example, let's say that for the moment you write your methods like this:
GetVoteCount(ReadablePerson p);
UpdatePersonDataFromLdap(ReadWritePerson p);
... but then in two years you decide to change to the wrapper implementation. Suddenly ReadOnlyPerson is no longer a ReadablePerson, because it's a wrapper class instead of an extension of a base class. Do you change ReadablePerson to ReadOnlyPerson in all your method signatures?
Or say you decide to simplify things and just consolidate all your classes into a single Person class: now you have to change all your methods to just take Person objects. On the other hand, if you had programmed to interfaces:
GetVoteCount(IReadablePerson p);
UpdatePersonDataFromLdap(IReadWritePerson p);
... then these methods don't care what your object hierarchy looks like, as long as the objects you give them implement the interfaces they ask for. You can change your implementation hierarchy at any time without having to change these methods at all.
Definitely do not make the read-only class inherit from the writable class. Derived classes should extend and modify the capabilities of the base class; they should never take capabilities away.
You may be able to make the writable class inherit from the read-only class, but you need to do it carefully. The key question to ask is, would any consumers of the read-only class rely on the fact that it is read-only? If a consumer is counting on the values never changing, but the writable derived type is passed in and then the values are changed, that consumer could be broken.
I know it is tempting to think that because the structure of the two types (i.e. the data that they contain) is similar or identical, that one should inherit from the other. But that is often not the case. If they are being designed for significantly different use cases, they probably need to be separate classes.
A quick option might be to create an IReadablePerson (etc) interface, which contains only get properties, and does not include Save(). Then you can have your existing class implement that interface, and where you need Read-only access, have the consuming code reference the class through that interface.
In keeping with the pattern, you probably want to have a IReadWritePerson interface, as well, which would contain the setters and Save().
Edit On further thought, IWriteablePerson should probably be IReadWritePerson, since it wouldn't make much sense to have a write-only class.
Example:
public interface IReadablePerson
{
string Name { get; }
}
public interface IReadWritePerson : IReadablePerson
{
new string Name { get; set; }
void Save();
}
public class Person : IReadWritePerson
{
public string Name { get; set; }
public void Save() {}
}
The question is, "how do you want to turn a modifiable class into a read-only class by inheriting from it?"
With inheritance you can extend a class but not restrict it. Doing so by throwing exceptions would violate the Liskov Substitution Principle (LSP).
The other way round, namely deriving a modifiable class from a read-only class would be OK from this point of view; however, how do you want to turn a read-only property into a read-write property? And, moreover, is it desirable to be able to substitute a modifiable object where a read-only object is expected?
However, you can do this with interfaces
interface IReadOnly
{
int MyProperty { get; }
}
interface IModifiable : IReadOnly
{
new int MyProperty { set; }
void Save();
}
This class is assignment compatible to the IReadOnly interface as well. In read-only contexts you can access it through the IReadOnly interface.
class ModifiableClass : IModifiable
{
public int MyProperty { get; set; }
public void Save()
{
...
}
}
UPDATE
I did some further investigations on the subject.
However, there is a caveat to this, I had to add a new keyword in IModifiable and you can only access the getter either directly through the ModifiableClass or through the IReadOnly interface, but not through the IModifiable interface.
I also tried to work with two interfaces IReadOnly and IWriteOnly having only a getter or a setter respectively. You can then declare an interface inheriting from both of them and no new keyword is required in front of the property (as in IModifiable). However when you try to access the property of such an object you get the compiler error Ambiguity between 'IReadOnly.MyProperty' and 'IWriteOnly.MyProperty'.
Obviously, it is not possible to synthesize a property from separate getters and setters, as I expected.
I had the same problem to solve when creating an object for user security permissions, that in certain cases must be mutable to allow high-level users to modify security settings, but normally is read-only to store the currently logged-in user's permissions information without allowing code to modify those permissions on the fly.
The pattern I came up with was to define an interface which the mutable object implements, that has read-only property getters. The mutable implementation of that interface can then be private, allowing code that directly deals with instantiating and hydrating the object to do so, but once the object is returned out of that code (as an instance of the interface) the setters are no longer accessible.
Example:
//this is what "ordinary" code uses for read-only access to user info.
public interface IUser
{
string UserName {get;}
IEnumerable<string> PermissionStrongNames {get;}
...
}
//This class is used for editing user information.
//It does not implement the interface, and so while editable it cannot be
//easily used to "fake" an IUser for authorization
public sealed class EditableUser
{
public string UserName{get;set;}
List<SecurityGroup> Groups {get;set;}
...
}
...
//this class is nested within the class responsible for login authentication,
//which returns instances as IUsers once successfully authenticated
private sealed class AuthUser:IUser
{
private readonly EditableUser user;
public AuthUser(EditableUser mutableUser) { user = mutableUser; }
public string UserName {get{return user.UserName;}}
public IEnumerable<string> PermissionNames
{
//GetPermissions is an extension method that traverses the list of nestable Groups.
get {return user.Groups.GetPermissions().Select(p=>p.StrongName);
}
...
}
A pattern like this allows you to use code you've already created in a read-write fashion, while not allowing Joe Programmer to turn a read-only instance into a mutable one. There are a few more tricks in my actual implementation, mainly dealing with persistence of the editable object (since editing user records is a secured action, an EditableUser cannot be saved with the Repository's "normal" persistence method; it instead requires calling an overload that also takes an IUser which must have sufficient permissions).
One thing you simply must understand; if it is possible for your program to edit the records in any scope, it is possible for that ability to be abused, whether intentionally or otherwise. Regular code reviews of any usage of the mutable or immutable forms of your object will be necessary to make sure other coders aren't doing anything "clever". This pattern also isn't enough to ensure that an application used by the general public is secure; if you can write an IUser implementation, so can an attacker, so you'll need some additional way to verify that your code and not an attacker's produced a particular IUser instance, and that the instance hasn't been tampered with in the interim.

Why are properties on classes in ASP.NET using C# generally public and properties using C# for desktop apps private?

I have searched high and low (and very possibly could have missed it), but in my years of programming, I have always come across one practice that seemed to be the standard in OOP, which is to use private properties in an object with public methods to manipulate the data.
However, the more I delve into ASP.NET (specifically with MVC), the more public properties I see inside of classes (specifically models) such as the ones shown at Scottgu's blog discussing the Entity Framework.
Does it have something to do with the way that LINQ populates a class?
Thanks in advance, and the answer may be out there, but I have been looking for a long time, and can't figure out why ASP.NET uses public and even the desktop C# apps use private.
You are confusing fields with properties. The concept of a property in .NET languages is basically an encapsulation of the get and set functions that you're describing.
For instance:
private int foo;
public int FooProperty
{
get { return foo; }
set { foo = value; ]
}
This is analagous to what you'd see otherwise like this:
private int foo;
public int getFoo()
{
return foo;
}
public int setFoo(int value)
{
foo = value;
}
It basically provides syntax that's similar to that of an ordinary field while providing the developer with control over the actual get and set behavior.
What may be further confusing you is that C# has a shorthand for automatic implementation of simple properties (like the one above). Doing this:
public int Foo { get; set; }
Is actually just a shorthand for this:
private int _foo;
public int Foo
{
get { return foo; }
set { foo = value; }
}
This allows you to use properties everywhere in your public-facing API without sacrificing the convenience of fields. This means that you can
Be consistent (all public members are exposed through properties, instead of a mix of properties and fields
Be flexible, so you can change the code behind the property to a full property at a later date (if the need arises) without changing the public-facing API and having to recompile any assemblies that referenced your type.
I think what you might be seeing is the Auto-Implement Property feature. This is a shortcut to expose data members as public so that you don't need to explicitly create a private data members. C# will creates a private data member for you.
Eg:
public string MyProperty { get; set; }
Is doing the same as:
public string _MyProperty;
public string MyProperty
{
get { return _MyProperty; }
set { _MyProperty = value; }
}
You could make your data members public and not use the shortcut but if you decided to change the implementation of the data member to have some logic then you would need to break the interface.
Be careful not to confuse Properties with Member variables. The standard in OOP was to have private "properties" when there was no concept of a property, only a member variable, then to wrap that member variable in a public method to get and set it's value. It's generally a bad idea to have a public member variable, but public properties are good practice because just like methods, they encapsulate your member variable.
It's also to do with how ASP.Net (and possibly also WPF, by extension? I don't know WPF but one could make a reasonable assumption) decides using reflection what you mean when you pass a string to it's databinding functions.
Given the following:
public class ImaginaryModel
{
public string Naomi { get; set; }
public string GetHeidi()
{
// do something here
}
public string Elle;
}
This databinding expression will work:
Eval("Naomi")
... whereas these will not:
Eval("GetHeidi")
Eval("Elle")
... because the implementation of databinding evaluation appears to be written against Type.GetProperties(). At least, this is my experience and understanding. The convention probably grew out of this.
Public Properties are the way the .NET community has elected to deal with this.
Note the difference here:
public int Property { get; set; } // C# auto-prop
public int Property; // C# "field"
The former is the standard way, and is generally accepted. A backing field can be added when necessary. The latter is typically avoided, since it doesn't have the get/set.
It's possibly a relic due to the nature of Asp.net WebForms - Properties on code-behind had to be protected at minimum, as the asp.net compiler generates wrapper classes for pages and user controls. The generated classes cannot access private properties, so protected or public is generally the way to go.
Since I'm not an MVC expert, I can't say for certain whether this still occurs in MVC - but I do know that in WinForms, the codebehind is just a partial class and there is no generation of a wrapper object, any private property is fully accessible by textboxes and the like.
Alternately, people could just be using public properties so they can more easily create proxy classes in unit testing environments (which is the main reason I would use them on a model).

Why use private members then use public properties to set them?

Seen a few examples of code where this happens:
public class Foo
{
string[] m_workID;
public string[] WorkID
{
get
{
return m_workID;
}
private set
{
m_workID = value;
}
}
}
What's the point of this?
Since the use m_workID unnescessary.
In general, the point is to separate implementation (the field) from API (the property).
Later on you can, should you wish, put logic, logging etc in the property without breaking either source or binary compatibility - but more importantly you're saying what your type is willing to do, rather than how it's going to do it.
I have an article giving more benefits of using properties instead of public fields.
In C# 3 you can make all of this a lot simpler with automatically implemented properties:
public class Foo
{
public string[] WorkID { get; private set; }
}
At that point you still have a public getter and a private setter, but the backing field (and property implementation) is generated for you behind the scenes. At any point you can change this to a "normal" fully-implemented property with a backing field, and you'll still have binary and source compatibility. (Compatibility of serialized objects is a different matter, mind you.)
Additionally, in this case you can't mirror the behaviour you want (the ability to read the value publicly but write it privately) with a field - you could have a readonly field, but then you could only write to it within the constructor. Personally I wish there were a similar shorthand for this:
public class Foo
{
private readonly int id;
public int Id { get { return id; } }
...
}
as I like immutable types, but that's a different matter.
In another different matter, it's generally not a good idea to expose arrays like this anyway - even though callers can't change which array WorkID refers to, they can change the contents of the array, which is probably not what you want.
In the example you've given you could get away without the property setter, just setting the field directly within the same class, but it would mean that if you ever wanted to add logging etc you'd have to find all those writes.
A property by itself doesn't provide anywhere to put the data - you need the field (m_workID) for storage, but it entirely correct to hide that behind a property for many, many reasons. In C# 3.0 you can reduce this to:
public string[] WorkID {get; private set;}
Which will do much of the same. Note that exposing an array itself may be problematic, as there is no mechanism for protecting data in an array - at least with an IList<string> you could (if needed) add extra code to sanity check things, or could make it immutable. I'm not saying this needs fixing, but it is something to watch.
In addition to the Object Oriented philosophy of data encapsulation, it helps when you need to do something every time your property is read/write.
You can have to perform a log, a validation, or any another method call later in your development.
If your property is public, you'll have to look around all your code to find and modify your code. And what if your code is used as a library by someone else ?
If your property is private with appropriate get/set methods, then you change the get/set and that's all.
You can use C# 3.0 auto properties feature to save time typing:
public class Foo
{
public string[] WorkID
{
get; private set;
}
}
In addition properties gives you lot of advantages in comparison to fields:
properties can be virtual
properties hide implementation details (not all properties are just trivial variable accessors)
properties can contain validation and logging code and raise change events
interfaces cannot contains fields but properties
A lot of times you only want to provide read access to a field. By using a property you can provide this access. As you mention you may want to perform operations before the field is accessed (lazy loading, e.g.). You have a lot of code in there that just isn't necessary anymore unless you're still working in .Net 2.0-.

Categories