Regarding simple inheritance in C# - 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.

Related

Why property can be contain only setter in interface type in C#?

I wonder why in C# it is not allowed to use only { set } property in auto-generated property in class type like:
class Person {
public string Name { set; } // Compile-time error
}
However, it is allowed in interface type:
interface IPerson {
string Name {set;} //Allowed
}
I read similar question here, it is very rare practice - what I understand, but I wonder why CLR even allow to do it?
For one simple reason. If you're using an Auto implemented property (Hidden private field generated). Then why would you need to set a value that you would never be able to get (and subsequently use).
For the Interface, you're not using an auto implemented property, it is just a contract specifying that the implementation class should have a string property named Name that should implement a Setter method. So, you can do this:
interface IPerson
{
string Name { set; }
}
class Person : IPerson
{
private string _name;
public String Name
{
set { _name = value; }
}
}
So in conclusion, the C# compiler is trying to prevent us from doing something that doesn't make any sense which is: Providing an auto set method for a private hidden field that can never be get.
Because what is the point of a property you can assign a value to but have no way to observe it?
The following is perfectly legal
class Person {
private string _name;
public string Name { set { _name = value } }
}
The reason the auto property doesn't let you do it is because you could never get the value out after it was written, with a manual implemented property you have the chance to set the value to some other field.
The reason interfaces allow it is so the interface can describe manually implemented versions or auto implemented ones with public string Name {private get; set;}.
You're using an autoproperty in your class, which is defined as having a hidden private field that is accessible using a getter.
If you're just using a normal property, you can absolutely have only a setter:
public string Name {
set {
Console.WriteLine("hi");
}
}
class Person {
public string Name { set; } // Compile-time error
}
The backing field is inaccessible, so there is no way to get it. It's explained in the C# specification that since there is no point in having one without the other, it is disallowed.
Because the backing field is inaccessible, it can be read and written
only through the property accessors, even within the containing type.
This means that automatically implemented read-only or write-only
properties do not make sense, and are disallowed. It is however
possible to set the access level of each accessor differently.
The compiler team made a call that it would be better to not allow it, since there is no point and by allowing it, developers can potentially write more error prone code.
They make the same judgement call in other areas of the language too, such as not allowing fall through most of the time in case statements. (you can fall through a case with no code in it). Technically, in that instance you could say it provides benefit, but they felt that the benefit did not outweigh the potential error cost.
The interface is only to make sure that your class is implementing the method. However, when you are creating a class, there is no point of having a property that you can never get

Properties vs Public member variables [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between a field and a property in C#
I'm a beginning programmer and I've read all about class properties. Books state that properties allow you to indirectly access member variables. Ok, so what makes it any different than just making the field public and accessing it directly?
Here's a quote from Learning C# 3.0 by Jesse Liberty:
For example, you might want external
classes to be able to read a value, but not change it; or you might want to write
some code so that the internal field can accept only values in a certain range. If you
grant external classes free access to your member fields, you can’t control any of that.
I don't understand what he is saying here. Can someone further explain this or give an example of why I would want to use a property over making the field public. As I understand it now they would both accomplish the same exact thing...so I'm obviously missing something here.
The other answers provided so far provide details of the advantages of accessor/mutator logic, but all seem to miss out on the ideological point about object encapsulation.
You see, class member fields are an implementation detail. If you have a class that represents a collection, for example, then you could implement it as a linked list (and expose the root-node via a public field) or you could implement it as a resizable array and expose the index0 member.
The problem with revealing implementation details is that you lose any kind of defined interface between your class and its consumers. By ensuring all operations are done via defined methods (controlled by the class itself) you make it easier to work with and provide for a long-term viewpoint. For example, you are far more easily able to convert your collection implementation from one type (the linked-list) to another (the array) without breaking any contracts with your class' consumers.
Don't worry about any performance impact of trivial accessor/mutator methods: the JIT compiler will inline the property methods. If you'll run some benchmarks you'll see the performance of properties vs fields is identical.
He's saying that properties can provide a getter but not a setter, therefore making them read-only (for example)
Properties are just syntactic sugar for a method e.g.
public int SomeProperty { get; set; }
is just sugar for
private int _someProperty;
public int SomeProperty_get()
{
return _someProperty;
}
public void SomeProperty_set(int value)
{
_someProperty = value;
}
This means that property setters/getters can apply logic that a mere public field can't
Edit: I'm not exactly sure what field names the CLR gives the backing fields for auto-properties - it's just an example :)
Edit2:
An example of a read only property:
public int SomeProperty { get; }
and finally a public read - private write (for autoproperties)
public int SomeProperty { get; private set; }
Really useful when you can't be bothered to type a backing field in :)
Just remember, if there is a possibility that you wish to apply logic to a member, then a property is the way to go. This is the way a lot of frameworks work (e.g. tracking 'dirty' objects by using a property to tell some sort of object manager that something has changed, this would not be possible using a public field)
Properties can have side-effects, They provide syntactic sugar around 'getter' and 'setter' methods.
public class MyClass {
int sizeValue = 0;
public int Size {
get {
return sizeValue;
}
set {
if ( value < 10 ) throw new Exception("Size too small");
sizeValue = value;
}
}
}
Properties can also have different levels of protection for get and set, you cannot do that with fields.
public class MyOtherClass {
// only this object can set this.
public int Level {
get; private set;
}
// only things in the same assembly can set this.
public string Name {
get; internal set;
}
}
There are a number of important differences between "properties" and "member access".
The most significant is that you can, through a property, make a member read-only (you can access the state, but you cannot change it). Just like "getter()" and "setter()" methods in Java.
You can also return a computed value from a property (generate a value "on-the-fly", as though it were a variable).
Properties can be configured so that:
they are read-only, Public MyProp {get;}
they are write-only Public MyProp {set;}
they are readable by external objects, but can only be set by the class's internals
Public MyProp {get; private set;}
As others have posted, you can also put logic into your getters and setters. For example before allowing the property to bet set to a new value, you can check that the value is acceptable.
You cannot do any of that with a public field.
Basically, a public field is the dumbest sort of property that you can have. Given that .Net now allows autobacking fields for your properties. There is no good reason to use public fields any longer.
If you have Public Int MyAge
I can set it to -200 or 20,000 and there is nothing you can do about it.
If you use a property you can check that age is between 0 and 150, for example.
Edit: as per IanNorton's example (man, that was fast)

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.

Is it possible to customize access modifiers behaviour?

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; }

Accessing Private variables in a child class?

So i was browsing some code and i came across:
public class Person
{
private string message;
public override string ToString()
{
return message;
}
public static Person CreateEmployee()
{
return new Employee();
}
class Employee : Person
{
public Employee()
{
this.message = "I inherit private members!";
}
}
}
Can someone please explain how the private variable "message" is being used/accessed even though its private??
Private members are accessible to all code within the class, including nested classes.
If you move the Employee class outside the Person class, it will fail until you make the field protected.
The simple fact is, this works because compilers allow it to - the designers thought it was a good thing. Once code is compiled, private/public variables are stored in memory in exactly the same way. (The CLR is simply aware of different metadata attributes for them.)
The justification is: nested classes and their members are still considered to lie conceptually/hierarchically within the parent class. Hence, private members of the parent class are always accessible by these semantics. Besides, it just makes life easy for programmers in many cases without breaking the object-oriented encapsulation rule!
In fact, if you want to think about this in terms of code, any code that falls within the open and close braces of a given class can access its private members, regardless of whether it immediately lies within a nested class/struct/etc.
Because Employee is an inner class of Person.
See this question: can-inner-classes-access-private-variables
Person={private message, private Employee}
Private Employee and private message are siblings, Employee can use the message. If you allocate Private Message into another class and mark it as protected/private outside the Person class, then Employee will not be able to see or use it anymore even with an instance of that class.

Categories