I am not sure if there is already a nomenclature for this, but for the sake of this question lets define two terms: peer implementation or nested implementation to illustrate how you implement collection classes in a data model that contains many parent/child entity relationships.
I use the term peer to describe the scenario where you implement the collection classes in your model layer along side with the entity classes essentially making them peers in your API like so:
public class ParentEntity
{
private ChildEntityCollection children;
}
public class ChildEntity
{
}
public class ChildEntityCollection : ICollection<ChildEntity>
{
}
The main advantage here is that you can reuse the collection class in other entity classes that happen to store children of the same type.
I use the term nested to describe the scenario where you implement them as a nested class like so:
public class ParentEntity
{
private ChildEntityCollection children;
public class ChildEntityCollection : ICollection<ChildEntity>
{
}
}
public class ChildEntity
{
}
The main advantage here is that each parent can implement their own collection class to store its children in manner that is most optimized for that specific parent. For example, one parent entity may find that an array data structure works well whereas another may use a splay tree (obscure I know, but it illustrates my point well).
I have noticed that Microsoft uses both idioms in the various .NET related frameworks. The System.Windows.Forms namespace seems to rely heavily on nested implementations. I tend to find myself prefering this method as well even though it requires more work.
Recommendations, comments, alternative ideas?
Regardless of what Microsoft might have done in the past, the current .NET API design guidelines discourage creation of nested classes that are visible outside their parent classes. See http://msdn.microsoft.com/en-us/library/ms229027.aspx for details.
Another option is to nest the collection class in the child class, and just name it Collection. That way, you always get Child.Collection as the name.
public class Child
{
public class Collection : ICollection<Child>
{
}
}
public class Parent
{
private Child.Collection children;
}
Personally I prefer the peer implementation, it promotes reuse of code which I don't think the nested implementation does. If another class needs to implement a different way of storing a collection of the same elements then another class can easily be implemented for that scenario without limiting code reuse.
A nested setup can also lead some developers to tightly couple their code to the parent class.
I also prefer the peer approach. There's really no reason to nest the collection unless you will never use it outside of its parent class (in that case, it should be a private nested class.)
I would only use the nested arrangement when there is only one Entity in the Domain model that can logically contain the child Entities.
For example if you had a PieceOfMail class and a MailPieces collection class
class PieceOfMail { }
class MailPieces: Collection<PieceOfMail> { }
then the ShipingCompany class, and the MailBox class, and the PostOffice Class, and the MailRoute class, and the MailManBag class, could ALL have a constituent property typed as MailPieces, so I'd use the "peer" technique.
But otoh, in the same Domain, if you had a class representing a type of PostageDiscount, and a collection class representing a set of discounts to be applied to a shipment, it might be the case that ONLY the ShipmentTransaction class could logically contain a collection of those discounts, then I'd use the nested technique...
Do you really need a ChildEntityCollection? Why not use a collection type that is provided?
//why bother?
//public class ChildEntityCollection : ICollection<ChildEntity>{}
public class ParentEntity
{
//choose one
private ChildEntity[] children;
private List<ChildEntity> childrenInList;
private HashSet<ChildEntity> childrenInHashSet;
private Dictionary<int, ChildEntity> childrenInDictionary;
// or if you want to make your own, make it generic
private Balloon<ChildEntity> childrenInBalloon;
}
public class ChildEntity
{
}
I generally try to avoid generating specific collection classes. Sometimes you may need a special class, but in many cases you can simply use generic classes like Collection<T> and ReadOnlyCollection<T> from the System.Collection.ObjectModel namespace. This saves a lot of typing. All your collections derive from IEnumerable<T> etc. and are easily integrated with LINQ. Depending on your requirements you could also expose your collections as ICollection<T> or another collection interface and then let classes with specific requirements use highly optimized generic collections.
public class ParentEntity {
Collection<ChildEntity> children = new Collection<ChildEntity>();
public Collection<ChildEntity> Children {
get {
return this.children;
}
}
}
You can also wrap an IList<T> like this:
public class ParentEntity {
// This collection can be modified inside the class.
List<ChildEntity> children = new List<ChildEntity>();
ReadOnlyCollection<ChildEntity> readonlyChildren;
public ReadOnlyCollection<ChildEntity> Children {
get {
return this.readOnlyChildren
?? (this.readOnlyChildren =
new ReadOnlyCollection<ChildEntity>(this.children));
}
}
}
Related
I'm a relative newbie to C#, although I am a competent programmer, and I confess that I am totally confused as to whether or not it is a good idea to write custom collection classes. So many people seem to say "don't", yet there is a whole set of base classes for it in C#.
Here is my specific case. I have a timetable application. As part of that, I have a service class, and the service class contains collections of things service-y, such as route links. A route link is itself a custom class:
public class Service
{
public RouteLinks RL; // A collection of RouteLink types
...
}
public class RouteLink
{
public string FirstStopRef;
public string LastStopRef;
public Tracks RouteTrack; // Another collection, this time of Track types
}
So far I have looked at using Dictionary as the type for RouteLinks, because I need to be able to reference them. This is fine in principle. However, the process of adding a RouteLink to the RouteLinks collection involves checking to see whether it is already there, or whether it extends and existing route link, or... And for that, I need a custom Add function.
So why is is such bad practice to create custom collection classes? Why shouldn't I just inherit CollectionBase or DictionaryBase?
I should perhaps add that I am transferring this code from VBA [please don't shoot me :)] and there I HAD to implement custom collections.
Instead of having RouteLinks be a collection type, an easy solution would be to just define another class, let's say RouteLinksRepository. This class will contain a List<RouteLink> and the AddRoute(RouteLink) functionality as well as any other custom logic for interacting with this collection of RouteLink objects. Your service class will then just contain an instance of this repository class.
public class Service
{
public RouteLinksRepository RL; // A collection of RouteLink types
// ...
}
public class RouteLinksRepository
{
public List<RouteLink> RouteLinks;
public bool AddRoute(RouteLink linkToAdd)
{
//Custom logic on whether or not to add link
}
//Your other logic for the class
}
public class RouteLink
{
public string FirstStopRef;
public string LastStopRef;
public Tracks RouteTrack; // Another collection, this time of Track types
}
If the only need is to check on double entries, a HashSet will do (implement a GetHash and Equals). However I guess you are trying to save a route. A route has a order, which means you have a order and List<> garantees the order. Make the collection objects private to hide the implementation.
public class Service
{
private List<RouteLink> RL; // A collection of RouteLink types
...
}
public class RouteLink
{
public string FirstStopRef;
public string LastStopRef;
private List<Track> Tracks; // Another collection, this time of Track types
}
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.
Given a class hierarchy such as:
Entity { id, name, position }
Combatant : Entity { health, strength }
Avatar : Combatant { connection }
Which are all immutable.
To implement 'move' on an entity I can return a new entity with a different position.
Entity Move(p) { return new Entity(id, name, p); }
However if I call 'move' on an Avatar, I will get an Entity, not an Avatar. So I have to implement 'move' on all immutable classes. Is there a way to avoid this, or a better solution?
you can resolve this with generics, i am assuming for the sake of simplicity that there are protected setters for all the properties:
Entity<InheritingType>
where InheritingType : Entity<InheritingType>
{
public T Move(Position newPosition)
{
T result = this.Clone();
result.Position = newPosition;
return result;
}
private T Clone()
{
//create a new instance of ourselves using reflection
//i.e. reflect all the protected properties in the type (or fields if you don't want even protected properties) , and set them
//you could also have the Clone method be abstract and force it's implementation in all inheriting types
}
}
To allow the current types to remain as they are you can do a simple inheritance of the generic base for each concrete type:
Entity : Entity<Entity>{}
Combatant<InheritingType> : Entity<InheritingType>{}
Combatant : Combatant<Combatant>{}
Avatar : Combatant<Avatar>{}
For a examples for deep cloning you can follow this link although i should point out that if performance is important, it would be better to require each inheriting class to override this method and add their own properties to the cloning process.
You need to decouple the logic of movement from your model. (always stick to SOLID principles). The rest is similiar to NightDweller's post
your code may look like this:
pubilc interface IMovementLogic<T> where T:Entity
{
T Apply(Position p);
//You can name the method anything else you like such as "Move" or "execute
}
public class EntityMovement : IMovementLogic<Entity> {...}
public class CombatantMovement : IMovementLogic<Combatant> {...}
public class AvatarMovement : IMovementLogic<Avatar> {...}
or
public class EntityMovement<T> : IMovementLogic<T> where T:Entity {...}
public class CombatantMovement : EntityMovement<Combatant> {...}
public class AvatarMovement : EntityMovement<Avatar> {...}
then implement this interface for ech of your classes.
depending on the algorithm of movement, you may also consider using decorator pattern.
Having tried to use immutable types extensively in some hobby projects, I came to the conclusion that in C#, they are quite a bit of effort except in the following special case: the type is a struct or a sealed class inheriting from object, and has no fields that are collections.
In all other cases I think immutable types are far more trouble than they are worth in C#, unfortunately, even though I'd rather like to use them more.
Are you sure you want this hierarchy of classes to be immutable?
It's already tricky, and the moment you add a property/field that is a collection your difficulties will shoot through the roof. For example, unless you do it very carefully, .Move will have to create deep copies of collections. But even if you are careful enough with .Move, replacing a single property of a single element in a collection will definitely require the whole collection to be copied. Etc...
This question already has answers here:
Why/when should you use nested classes in .net? Or shouldn't you?
(14 answers)
Closed 10 years ago.
Specifically, can anyone give me concrete examples of when or when not to use nested classes?
I've known about this feature since forever, but never had a reason to use it.
Thanks.
When the nested class is only used by the outer class, a great example, no longer necessary, is for an enumerator class for a collection.
another example might be for a enum to replace a true false parameter used by a method within a class, to clarify the call signature...
instead of
public class Product
{
public void AmountInInventory(int warehouseId, bool includeReturns)
{
int totalCount = CountOfNewItems();
if (includeReturns)
totalCount+= CountOfReturnedItems();
return totalCount;
}
}
and
product P = new Product();
int TotalInventory = P.AmountInInventory(123, true);
which leaves it unclear as to what 'true' means, you could write:
public class Product
{
[Flags]public enum Include{None=0, New=1, Returns=2, All=3 }
public void AmountInInventory(int warehouseId, Include include)
{
int totalCount = 0;
if ((include & Include.New) == Include.New)
totalCount += CountOfNewItems();
if ((include & Include.Returns) == Include.Returns)
totalCount += CountOfReturns();
return totalCount;
}
}
product P = new Product();
int TotalInventory = P.AmountInInventory(123, Product.Include.All);
Which makes the parameter value clear in client code.
The two places where I use nested classes:
The nested class is used exclusively by the outer class, and I want completely private scope.
The nested class is used specifically to implement an interface defined elsewhere. For example, implementing an enumerator falls into this category.
You really only want to use nested classes when you are sure the nested class doesn't make sense that it would be used anywhere else.
For example, if you needed to create a list of several types of object associated together with functions and member information about that set of objects for a short time (like methods or properties), you could use a nested class to do that. Maybe you need to create a list of all combinations of some type of object, and then mark all combinations that have a certain property. That would be a good case for a nested class.
If you don't need methods on the nested class, you can probably just use a struct but I don't know if IL treats them any differently.
I sometimes use this for simple helper classes that I need for a function or two inside of the parent class.
For a practical example, see this question asked earlier this morning:
Make an object accessible to only one other object in the same assembly?
Summary: you can nest an associated data class inside it's business object.
I've seen cases of nested classes when a special purpose data structure is used only within one class, or a certain exception is thrown and caught only within one class.
I nest classes when I have a helper class which has no need to be visible to any other object in the system. This keeps the visibility as constrained as possible which helps prevent unintended uses of the class
Following Uncle Bob's 'rules' on cohesion should find that you actually create quite a number of nested (and nested, nested!) classes. These could be made non-nested but only if you have other clients that reference them now.
I'd like to improve on my previous answer!
A specific area where I use nested classes regularly is enabling Interface Injection and Inversion of Control. Example...
public class Worker
{
private IHelper _helper;
public Worker()
: this (new DefaultHelper())
{
}
public Worker(IHelper helper)
{
this._helper = helper;
}
private class DefaultHelper : IHelper
{
}
}
Lets say I inherit a class, that has several public properties and/or methods, however I do not want them to be public properties/methods of my class - in other words, I want to make those properties protected properties of my class.
Can this be achieved?
I hope I was clear enough, if not please let me know, will try to explain myself better.
EDIT:
Right, thank you all for answers however I don't think I was clear enough. What I am trying to accomplish is this:
I wrote a windows control that extends ListView control. ListView has a public collection Items, that can be modified. That's all fine, however I wrote new methods for adding items to listview because of the extra data I need.
It all works great so far, however the Items collection can still be modified by anything, which is a problem, because if an item is added by direct manipulation of Items collection not all data I need is gathered, thus causing an error.
Since we hope to reuse this control several times in different projects, we are afraid that sooner or later, the default way of adding items to Items collection will be used (just a matter of time really). We are just looking for a way to prevent that from happening, like throwing an exception when Items collection gets bigger, but the way it was intended.
I hope this all makes sense now.
Never say never. This is probably not the best idea but it seems to work for me. This hides items by re-implementing it in the subclass and then hiding it using attributes. I added in a "CustomExposedItems" property so you can see that the existing items are still accessible in the underlying ListView.
public partial class CustomListView : ListView
{
public CustomListView()
{
InitializeComponent();
}
public System.Windows.Forms.ListView.ListViewItemCollection CustomExposedItems
{
get
{
return base.Items;
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Obsolete("Use the new custom way of adding items xyz")]
public new System.Windows.Forms.ListView.ListViewItemCollection Items
{
get { throw new NotSupportedException(); }
}
}
Inheritance is all about saying "You can use this derived class in the same way as you can use the base class, and it provides specialized behaviour."
If you can't use the derived class in the same way as the base class, then you shouldn't be using inheritance: you're breaking Liskov's Substitutability Principle. In such a case, use composition instead of inheritance. (Personally I don't use class-to-class inheritance that much anyway, far preferring composition - I find there are relatively few cases where the specialization aspect really works without issues. When it does work it's great though!)
No, you cannot do that. The best you can do is creating a class and wrap the base class insted of deriving from it - but this will of course break inheritance. (I assume you cannot modify the base class. If you can, you should rethink the design because it looks like your new class should not derive from the base class.)
class BaseClass
{
public String IWantThis { get; set; }
public String IDoNotWantThis { get; set; }
}
class MyClass
{
private BaseClass baseClass = new BaseClass();
public String IWantThis
{
get { return this.baseClass.IWantThis; }
set { this.baseClass.IWantThis = value; }
}
}
You can't do this by inheritance. This is actually what inheritance is about. An is-a relation cannot reduce the interface. The derived class must be a full representation of the base class.
Turn your inheritance into a reference. You reuse the implementation of your "base class" by calling it. (Composition instead of inheritance.) If you need polymorphism, add a common interface or move the common part into a separate abstract base class.
I not use AOP, perhaps PostSharp, to put around the Property you don't want used, and then you can handle it in some appropriate fashion with your aspect.