Correct implementation of an indexer on a derived class - c#

I have a class, say DerivedBindingList<T>, which is derived from BindingList<T>.
I would like to use an indexer with the derived class, and have coded it as:
public T this[int index]
{
get
{
// Getter code
}
set
{
// Setter code
}
}
However, the compiler complains with the following message: "...hides inherited member 'System.Collections.ObjectModel.Collection.this[int]'. Use the new keyword if hiding was intended."
I can add the 'new' keyword and the compiler is happy, but should I be doing things differently in some way to avoid this warning?
Perhaps I have to use base.this[] somehow?
Thanks.

The indexer in BindingList isn't virtual, so you can't override it - you'll have to just hide it if you really want to do this.
I don't think I'd advise it though - member hiding is a recipe for confusing code. What are you trying to do? Do you definitely want to derive from BindingList<T> instead of composing it (i.e. having a member of your class of type BindingList<T>)? What is your new indexer going to do?

This warning shows that an indexer already exists in base class.If you want to change its behavior you should either override it (if it's defined as virtual in base class) or use new keyword to tell the compiler to use derived indexer method whenever it's working with an instance of derived class.

Related

CA1033 with Properties

When I run code analysis (VS2013) with the 'Microsoft Managed Recommend Rules' rule set, the only warnings I get for my class library are of type CA1033: 'Interface methods should be callable by child types'. But I don't understand the rule in this situation:
/// An object that has a chemical formula
public interface IChemicalFormula
{
/// The chemical formula of the object
ChemicalFormula ChemicalFormula {get;}
}
public class ChemicalFormula: IChemicalFormula
{
ChemicalFormula IChemicalFormula.ChemicalFormula
{
get { return this; }
}
}
The docs recommends making a protected method with the same name so that deriving types can access it, but you cannot name a method the same as the enclosing type. They also recommend making the class sealed, but I don't want it to be sealed in this case. Is this a time just to ignore this rule, or is there an appropriate way to handle it?
EDIT
To add clarification why the class/interface is designed this way, I have another class, Peptide that contains a IChemicalFormula[] array to store modifications. Not every modification necessarily derives directly from ChemicalFormula, but they need to implement the IChemicalFormula interface. Therefore, if I modify an instance of a peptide withsome molecule (H2O for example), then ChemicalFormula class needs to also implement IChemicalFormula.
This is the description of the rule:
Consider a base type that explicitly implements a public interface
method. A type that derives from the base type can access the
inherited interface method only through a reference to the current
instance (this in C#) that is cast to the interface. If the derived
type re-implements (explicitly) the inherited interface method, the
base implementation can no longer be accessed. The call through the
current instance reference will invoke the derived implementation;
this causes recursion and an eventual stack overflow.
I think you should consider evaluating the usage of this property. A good example where TDD could be used to figure out the interface. There are some possible usages (and some invalid ones) below. I am not yet sure what you intend to achieve by looking at those.
In your example, let's say another class, NewChemicalForumla is derived from ChemicalForumula, and references ChemicalFormula, what does that mean?
public class NewChemicalFormula: ChemicalFormula
{
public void Method()
{
Console.WriteLine("{0}", ChemicalFormula.GetType()); // Compile error
Console.WriteLine("{0}", this.ChemicalFormula.GetType()); // Effectively same as above, compile error
Console.WriteLine("{0}", ((IChemicalFormula)this).ChemicalFormula.GetType()); // Works, is that what you intend?
}
}
Now from outside the class, there are two possibilities:
When you have a handle to a derived class:
new NewChemicalFormula().ChemicalFormula.GetType() // Error
or
// This works, is that what you intend to achieve?
((IChemicalFormula)new NewChemicalFormula()).ChemicalFormula.GetType()
When you have a handle to the IChemicalFormula already. In this case, ChemicalFormula seems redundant:
IChemicalFormula formula = new NewChemicalFormula();
Console.WriteLine("{0}", formula.GetType()); // Works, returns NewChemicalFormula
Console.WriteLine("{0}", formula.ChemicalFormula.GetType()); // Works, returns NewChemicalFormula
Console.WriteLine("{0}", formula.ChemicalFormula.Method()); // Compile error
formula.ChemicalFormula.Method() leads to an error because you must cast it to NewChemicalFormula before you can use Method(). Just because the property returns this doesn't help solve this problem.
So the FXCop warning is worth considering, and evaluating the design.

Preventing a C# subclass from overwriting a method

Say I have an abstract parent class called "Parent" that implements a method called "DisplayTitle". I want this method to be the same for each subclass that inherits "Parent" - I would like a compile error if a subclass attempts to implement their own "DisplayTitle" method. How can I accomplish this in C#. I believe in Java, I'd just mark the method as "final", but I can't seem to find an alternative in C#. I've been messing around with "sealed" and "override", but I can't get the behavior that I'm looking for.
For example, in this code:
using System;
namespace ConsoleApplication1
{
class Parent
{
public void DisplayTitle() { Console.WriteLine("Parent's Title"); }
}
class ChildSubclass : Parent
{
public void DisplayTitle() { Console.WriteLine("Child's Own Implementation of Title");
}
static void Main(string[] args)
{
ChildSubclass myChild = new ChildSubclass();
myChild.DisplayTitle();
Console.ReadLine();
}
}
}
I'd like to receive a compile error saying that the "ChildSubClass" can't override "DisplayTitle". I currently get a warning - but it seems like this is something that I should be able to do and I don't know the proper attributes to label the method.
How can I accomplish this in C#. I believe in Java, I'd just mark the method as "final", but I can't seem to find an alternative in C#.
The rough equivalent is sealed in C#, but you normally only need it for virtual methods - and your DisplayTitle method isn't virtual.
It's important to note that ChildSubclass isn't overriding DisplayTitle - it's hiding it. Any code which only uses references to Parent won't end up calling that implementation.
Note that with the code as-is, you should get a compile-time warning advising you to add the new modifier to the method in ChildSubclass:
public new void DisplayTitle() { ... }
You can't stop derived classes from hiding existing methods, other than by sealing the class itself to prevent the creation of a derived class entirely... but callers which don't use the derived type directly won't care.
What's your real concern here? Accidental misuse, or deliberate problems?
EDIT: Note that the warning for your sample code would be something like:
Test.cs(12,19): warning CS0108:
'ConsoleApplication1.ChildSubclass.DisplayTitle()' hides inherited
member 'ConsoleApplication1.Parent.DisplayTitle()'. Use the new keyword
if hiding was intended.
I suggest you turn warnings into errors, and then it's harder to ignore them :)
A derived class cannot override your method, you didn't declare it virtual. Note how that's very different in C# compared to Java, all methods are virtual in Java. In C# you must explicitly use the keyword.
A derived class can hide your method by using the same name again. This is probably the compile warning you are talking about. Using the new keyword suppresses the warning. This method does not in any way override your original method, your base class code always calls the original method, not the one in the derived class.
Use the sealed modifier to prevent subclasses from overriding your classes, properties, or methods. What isn't working when you use sealed?
http://msdn.microsoft.com/en-us/library/88c54tsw.aspx
I'm fairly certain that what you want is not possible in C# using method modifier keywords.
Sealed only applies when overriding a virtual method in an ancestor class, which then prevent further overriding.

Difference between new and override?

I have a base class which I want to provide some 'base' functionality for methods for all inheriting classes.
In my inheriting classes I want to do:
public override void Setup()
{
base.Setup();
}
But at the moment it says I have to use the new keyword.
How to I have it so I have to use the override keyword?
Is there any difference between how it is currently with me using the new keyword and using override?
It says so because you have not declared the base method virtual. Once you do so, the base virtual/derived override pair of keywords will make sense. Right now, the compiler is complaining that you cannot override a non-virtual method.
When you use the override keyword the derived method is used even when the instance is passed as a Base class type. Hence there needs to be a virtual in the base class so that the programme knows it has to make a runtime check of what the actual type of the instance is. It then looks up what the actual type is and if it is a derived type it checks if their is an override in the derived class for that particular method in the base class.
Member hiding is different. The base member will only be hidden if it is actually passed as an instance of the derived class. If the object is passed as a base class, the base class method will still be used. If you hide a member, you get a warning if you haven't use the new keyword. The new keyword is merely to tell the complier, that you really do mean to hide the base type method.

Hide Virtual function In Inherited Class

I have a class that inherits from LinkButton and I want to hide OnClinentClick from my class.
Somthing like this :
public class MyClass : LinkButton
{
// some Code
}
And somewhere in code:
MyClass myclass = new MyClass();
MyClass.OnClinentClick = "";//this line must not be accessable
Hiding something from a class definition is not directly supported as it breaks OOP principles.
You could use the new operator, however, I wouldn't advise it. Personally, I would think about my design and/or use a NotSupportedException if there is no other way around it.
You can use the EditorBrowsableAttribute to prevent it from being suggested by IntelliSense, but you can't get rid of it entirely.
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual string OnClientClick { get; set; }
C# only supports public inheritance. You shouldn't be inheriting from a class whose methods don't make sense for all derived classes. Consider composition instead of inheritance to solve this problem.
You can override the function (that is, replace the base implementation with your one, as long as the former is virtual), but you cannot completely prevent the clients from calling the base class function if you hide it with new, as they may always cast to the base class.
Update:
actually, you cannot change the access from public to protected/private when overriding, this won't compile (http://ideone.com/Y65Uh). Besides that, if you use new to hide the base function and make it uncallable, the original function is still visible (http://ideone.com/xiL2F). If you declare the new function public (which is perhaps not what you want), the old function can still be called by casting to the base class (http://ideone.com/A3Bji).
How about making giving it a lower visibility. One of protected and internal might be what you want. Of course that doesn't remove such a member from the derived class, but just removes them from the public interface. It also requires control over the base-class. No idea if LinkButton is one of your classes.
You could also hide the property by reintroducing a new one with the same. But that's a bad idea, and casting back to the base-class allows outsiders to access it.
And you should consider using a has-a relationship instead of an is-a. i.e. Don't derive from a base class if you don't want all its public members. This violates OOP principles such as that it should be possible to substitute the derived class where the base class is expected.
You could also override it, and make the setter throw a NotSupportedException. But that's ugly too because it will only show an error at runtime instead of compiletime. You can generate compile-time warnings with attributes such as the ObsoleteAttribute.

Whats the effect of new keyword in return type of a C# method?

Accidently I actually wrote this method:
public static new iTextSharp.text.Color ITextFocusColor()
{
return new iTextSharp.text.Color(234, 184, 24);
}
It is working as suspected, but I was very surprised that is it allowed to use the new keyword in the return type of the method. Is there any effect/difference if i put there new or not? Or what is the new used for?
And is this also possible in other OO-languages?
It doesn't affect the return type, it indicates that this method hides the method from the base class (rather than override it). It can be useful if you need to change the return type declared in the base class, for instance, but the hiding method won't participate in polymorphism, i.e. if you call ITextFocusColor on an instance of the derived class through a variable of the base class, the base implementation will be called (not the one declared with new)
See this page on MSDN for more details.
The new keyword specifies that you are deliberately providing a new implementation of a method or property that is already provided by a base class. It's there to make hiding of base class members a deliberate, self-documenting act.
If your base class doesn't have that method, it doesn't actually matter.
For more details, see the C# specification (specifically, section 3.7.1.2 Hiding through inheritance).
It is the new modifier. It hides members from a base class instead of overriding.
new keyword in method return type here hides the parent method.

Categories

Resources