"Use the new keyword if hiding was intended" warning - c#

I have a warning at the bottom of my screen:
Warning 1 'WindowsFormsApplication2.EventControlDataSet.Events' hides
inherited member
'System.ComponentModel.MarshalByValueComponent.Events'. Use the new
keyword if hiding was intended. C:\Users\myComputer\Desktop\Event
Control\WindowsFormsApplication2\EventControlDataSet.Designer.cs 112 32 eventControl
If i double click on it, it comes up with:
public EventsDataTable Events {
get {
return this.tableEvents;
}
Can anyone tell me how to get rid of this?

Your class has a base class, and this base class also has a property (which is not virtual or abstract) called Events which is being overridden by your class. If you intend to override it put the "new" keyword after the public modifier. E.G.
public new EventsDataTable Events
{
..
}
If you don't wish to override it change your properties' name to something else.

#wdavo is correct. The same is also true for functions.
If you override a base function, like Update, then in your subclass you need:
new void Update()
{
//do stufff
}
Without the new at the start of the function decleration you will get the warning flag.

In the code below, Class A implements the interface IShow and implements its method ShowData. Class B inherits Class A. In order to use ShowData method in Class B, we have to use keyword new in the ShowData method in order to hide the base class Class A method and use override keyword in order to extend the method.
interface IShow
{
protected void ShowData();
}
class A : IShow
{
protected void ShowData()
{
Console.WriteLine("This is Class A");
}
}
class B : A
{
protected new void ShowData()
{
Console.WriteLine("This is Class B");
}
}

The parent function needs the virtual keyword, and the child function needs the override keyword in front of the function definition.

this warning also triggers when you have: x:Name="Name1" with Text="{Binding Name1}" the Same Property Name in same Element in your <Xaml> which can cause a serious conflict at a certain point when your binding process become more complex.

Related

If methods are neither virtual nor sealed by default, then why does this method override of a non-virtual and non-sealed method work?

On several occasions, I've been told that methods in C# classes are neither sealed nor virtual by default. Despite this, the follow code works just fine and prints the two clearly intended strings. This is strong evidence that I've very confused. What default or feature am I ignorant of?
Child ExampleChild = new Child();
ExampleChild.SayHello();
Parent ExampleParent = new Parent();
ExampleParent.SayHello();
public class Parent
{
public void SayHello() => Console.WriteLine("Hello from parent");
}
public class Child : Parent
{
public void SayHello() => Console.WriteLine("Hello from child");
}
You're defining a new method (Child.SayHello()), which hides the parent method. There's a compiler warning telling you so.
The new method should ideally be marked with new to make the intention clear. It won't partake in dynamic dispatch, i.e. if you have a variable of type Parent, then Parent.SayHello() will be called.
See also C# Inheritance and Member Hiding.

Composite pattern in C++ and C# - protected virtual methods

How can I add a protected virtual method in the "Component" class, so that it can be called from the "Composite"?
As an concrete example, look at the code below, and please tell me how to avoid the compiler error in DxCompositeShape.ComputeSize.
abstract class DxShape // this is the Component
{
public abstract void Paint();
protected abstract void ComputeSize();
}
class DxCompositeShape : DxShape // this is the Composite
{
public readonly IList<DxShape> Shapes = new List<DxShape>();
public override void Paint()
{
this.ComputeSize();
}
protected override void ComputeSize()
{
foreach (DxShape sh in Shapes)
{
sh.ComputeSize(); // compiler error CS1540
}
// and some other logic here
}
}
EDIT: I modified my sample, so I have ComputeSize instead of Init (people assume that Init can always be called in a constructor).
You can't. A protected member of a different object can only be invoked if the compiler can see that the object in question is of the same type as your current object. Basically, "protected" means "Derived classes can use this member in their own class.
The underlying issue here is that you want some privileged classes ("composites") to be able to call a method of foreign classes ("components") that the base class declares is only for use of derived classes in their own implementation.
You might want to make Init internal, if all composites are in the same package. Or maybe make a subclass of the component that all composites inherit, and make this particular class privileged to call Init on all components. In C++ you would do such a thing with friend declarations. In C#, careful use of internal access is probably the right solution.
Create a non-virtual function Initialise() in the base class that calls Init
eg:
abstract class DxShape
{
protected void Initialise()
{
Init();
}
protected abstract void Init();
//...
}
As pointed out in the comments below, Initialise must be made either public or static (only in C#), it may remain protected in C++.
In C++ you could then make Init private and only access it via calls to Initialise. See non-virtual interface http://en.wikipedia.org/wiki/Non-virtual_interface_pattern

How do you call a child protected method from the base class with dynamic

Got the following code
protected virtual void InternalChange(DomainEvent #event)
{
((dynamic) this).Apply(#event);
}
child objects implement the logic to handle events via a number of fields eg
protected Apply ( Message1 message)
{
}
protected Apply ( Message2 message)
{
}
however this gives an error saying its inaccessible. I tried virtual but no luck..
Any ideas ? .. hopefully without reflection like this method. ( eg http://blogs.msdn.com/b/davidebb/archive/2010/01/18/use-c-4-0-dynamic-to-drastically-simplify-your-private-reflection-code.aspx)
More information I can move the InternalChange to the child class but id rather not have the child doing the dispatch.
void Apply(AggregateRootHandlerThatMeetsConventionEvent domainEvent)
{
OnAggregateRootPrivateHandlerThatMeetsConventionCalled = true;
}
void Apply(AggregateRootPrivateHandlerThatMeetsConventionEvent domainEvent)
{
OnAggregateRootPrivateHandlerThatMeetsConventionCalled = true;
}
void Apply(AggregateRootProtectedHandlerThatMeetsConventionEvent domainEvent)
{
OnAggregateRootProtectedHandlerThatMeetsConventionCalled = true;
}
protected override void InternalChange(DomainEvent #event)
{
Apply(((dynamic)#event));
}
Edit for now i'm using this in the child ( and made the parent abstract) which works but its ugly id rather implementers not worry about the dispatch .
protected void Handle(DomainEvent message)
{
Handle ( (dynamic) message);
}
You should define your base class to have either abstract or virtual on the method signature, for instance.
protected abstract void Apply(Message1 message);
Use virtual if you want to define an implementation in your base class that doesn't have to (but can) be overridden in the child class.
In your subclass, you would override it as such:
protected override void Apply(Message1 message)
{
// code here
}
Also, in your example, the method InternalChange is trying to call Apply with an argument of type DomainEvent, however, in both your overloads for Apply, they accept either type of Message1 or Message2. If it did compile, you would get a run time error anyway because the .NET dynamic run time would not be able to find an appropriate method that matches the argument.
As for using dynamic, I think it is unnecessary for the problem at hand.
The logic is sort of... reversed. I don't understand one or two things: what class is calling apply, the base type or the child type? How the discerning of the child class to send the event to happens? Couldn't you render Apply virtual protected and leave it empty in the base class?

Why do I need to declare a Virtual Method when I can Hide it in derived Class

class clsTestParent
{
public void testNoAbstract()
{
Console.WriteLine("Parent Method Call");
}
}
class clsDerivedTest : clsTestParent
{
public void testNoAbstract()
{
Console.WriteLine("Child Method Hiding Parent Method");
}
}
clsTestParent objParent = new clsTestParent();
clsTestParent objOfParentFromDerived = new clsDerivedTest();
clsDerivedTest objDerived = new clsDerivedTest();
objParent.testNoAbstract();
objOfParentFromDerived.testNoAbstract();
objDerived.testNoAbstract();
Output:
Parent Method Call
Parent Method Call
Child Method Hiding Parent Method
But when I declare testNoAbstract() as virtual and over ride in derived class , then the out put will be as below:
Parent Method Call
Child Method Hiding Parent Method
Child Method Hiding Parent Method
Earlier I used to think , we can only redefine a method in derived class , if that is defined as abstract or virtual , but as can see now , we can hide the parent class method just by redefining it in derived class.
Though , I can see , the difference in output by changing the code , I would like to know , What are the differences between above two methods and why it yields different out put.
If youll ever do clsTestParent a = new clsDerivedTest () - you'll never be able to execute the one in the clsDerivedTest class !!!!
Thats the difference and thats why the compiler warns you.
you'll actually gonna do that if you wish to preform a Polymorphism architecture.
Microsoft tells you : " listen , you direved a class , and we will give you all the public things etc but we dont know how do you want to implement the methods ... if you'll use the virtual + override - youll be able to execute a different method via the instace type. and if you wont override - so the function of the father will always be executed.... its your choice ... we are warning you "... and they do warn
This is why 'redefinition' is somewhat bad word for that. Virtual call resolves your type runtime, that's why you were able to:
clsTestParent objOfParentFromDerived = new clsDerivedTest();
objOfParentFromDerived.testAbstractOrVirtual(); // marked as virtual or abstract in base class
and the call was resolved in runtime, to the method defined in a class that objOfParentFromDerived really is (new operator - clsDerivedTest), and not to the method defined in a class it was declared with(clsTestParent).
If it's not marked neither virtual or abstract then the compiler warns you, because the call will be resolved basing on the type the variable has been declared with.

C# - Call Method in Base Class

I have 2 classes:
public class A
{
public void WriteLine(string toWrite) { Console.WriteLine(toWrite); }
}
public class B : A
{
public new void WriteLine(string toWrite) { Console.WriteLine(toWrite + " from B"); }
}
In my code I do the following:
B writeClass = new B();
writeClass.WriteLine("Output"); // I expect to see 'Output from B'
A otherClass = (A)writeClass;
otherClass.WriteLine("Output"); // I expect to see just 'Output'
I presumed this would work because of polymorphism.
However, it always writes 'Output from B' every time. Is there anyway to get this to work the way I want it to?
EDIT Fixing code example.
When you "hide" a method from the base class using NEW you are just hiding it, thats it. It's still called when you explicitily call the base class implementation.
A doesnt contain WriteLine so you need to fix that. When I fixed it I got
Output from B
Output
namespace ConsoleApplication11
{
class Program
{
static void Main(string[] args)
{
B writeClass = new B();
writeClass.WriteLine("Output"); // I expect to see 'Output from B'
A otherClass = (A)writeClass;
otherClass.WriteLine("Output"); // I expect to see just 'Output'
Console.ReadKey();
}
}
public class A
{
public void WriteLine(string toWrite) { Console.WriteLine(toWrite); }
}
public class B : A
{
public new void WriteLine(string toWrite) { Console.WriteLine(toWrite + " from B"); }
}
}
Your method on class A is Write, not WriteLine. Change it to the same name and it will work as you expect. I just tried it and get:
Output from B
Output
Polymorphism (C# Programming Guide) explains this quite well. (This is the newer version of the original poster's link.) The page shows examples where a derived class overrides a virtual member and where new members hide base class members.
There appears to be some confusion over the new modifier. From the documentation:
Although you can hide members without the use of the new modifier, the
result is a warning. If you use new to explicitly hide a member, it
suppresses this warning and documents the fact that the derived
version is intended as a replacement.
Note that the hidden member does not need to be virtual.
Best practices:
Strongly prefer overriding to hiding. Polymorphic calls are idiomatic in OO languages.
If you intend to hide a member, always use the new modifier.
Never release code with compiler warnings.
If every developer on your team agrees that a compiler warning cannot be fixed, suppress it.
Don't use new keyword when you override the method in class B. And declare the method in A as virtual.
The 'new' keyword is making B's implementation of WriteLine overwrite A's implementation.
Don't accept this as an answer, but in my experience, it's almost always a mistake to use the 'new' keyword in this fashion. It's less readable and muddy's the clarity of your code.
Your class A has a Write function instead of WriteLine
public class A
{
public virtual void WriteLine(string toWrite) { Console.WriteLine(toWrite); }
}
public class B : A
{
public override void WriteLine(string toWrite) { Console.WriteLine(toWrite + " from B"); }
}
First: I guess you wanted to name the methods both "WriteLine" but the one in class A is only named "Write". And second: yes you inherit B from A but the object will still be of type "B" so now I don't think what you want is possible.

Categories