C# Running Casted Method Instead of Actual Method - c#

I have types of ViewComponents that extend a single ViewComponent class. In my View I have it looping over ViewComponents and printing them. Unfortunately it's pulling the casted methods instead of the actual class methods. Ex:
using System;
namespace test
{
class Component {
public string getType() {
return "Component";
}
}
class ButtonComponent: Component {
public string getType() {
return "Button";
}
}
public class test
{
public static void Main() {
Component[] components = new Component[1];
components [0] = new ButtonComponent();
Console.WriteLine(components[0].getType()); // prints Component
}
}
}
How can I get the button to print "Button" instead of "Component"?

You are defining two separate instance methods, Component.getType() and ButtonComponent.getType(). You most likely got a compiler warning about this as well, something to the effect of "Method ButtonComponent.getType() hides method from base class. Use the new keyword if this is intended." This warning is letting you know about the behavior you are experiencing, and there's a page about it in the documentation too.
What you want to do instead is declare a virtual method on the base class and override it in the subclass:
class Component {
public virtual string getType() {
return "Component";
}
}
class ButtonComponent: Component {
public override string getType() {
return "Button";
}
}
This way the implementation of ButtonComponent.getType() replaces that of the base type.
Side note: In general the accepted convention for method names is PascalCase (not camelCase). Consider renaming your method GetType() with a capital G.

Use virtual and override keywords:
class Component {
public virtual string getType() {
return "Component";
}
}
class ButtonComponent: Component {
public override string getType() {
return "Button";
}
}
:)

Related

How to Override a Virtual method with Object type in the parameter

I want to override BuildFilter Method in the derived class. I have a virual BuildFilter Method with the following signatures
public abstract class BaseSearchProperty <TEntity> : ISearchResultProperty<TEntity>
{
public virtual List<AppliedFilter> BuildFilter(object value)
{
return new List<AppliedFilter>();
}
}
i know the BuildFilter method override types one is string and another one is a List of String List<string>. i have written the override methods in the derived class as below
public class IndustrySearchProperty : BaseSearchProperty<API.ISearchResult>
{
public override List<AppliedFilter> BuildFilter(string filterValue,)
{
var appliedFilters = new List<AppliedFilter>();
return appliedFilters;
}
public override List<AppliedFilter> BuildFilter(List<string> filterValue)
{
var appliedFilters = new List<AppliedFilter>();
return appliedFilters;
}
}
but am getting error like no suitable method found to override. I know what this error is both parent class signature and child class signature needs to be same. Is there any other way that i solve this problem??
both parent class signature and child class signature needs to be same
Yes. There is no clean way.
Two things you can do:
Get the object in the overrided method and cast to whatever type needed or
Add a new type parameter
like this:
public abstract class BaseSearchProperty <TEntity,TFilter> : ISearchResultProperty<TEntity>
{
public virtual List<AppliedFilter> BuildFilter(TFilter value)
{
return new List<AppliedFilter>();
}
}
I recommend neither. This is a code smell in my mind showing you are not using inheritance correctly. And it probably doesn't support Liskov and other principles.

Why do we use virtual and override?

Why do we use override and virtual if it gives the same effect when we dont use override and virtual?
example 1:
class BaseClass
{
public virtual string call()
{
return "A";
}
}
class DerivedClass : BaseClass
{
public override string call()
{
return "B";
}
}
output : B
Example 2:
class BaseClass
{
public string call()
{
return "A";
}
}
class DerivedClass : BaseClass
{
public string call()
{
return "B";
}
}
and the output is still the same:
output : B
to run the test:
class Program
{
static void Main(string[] args)
{
DerivedClass dc = new DerivedClass();
Console.WriteLine(dc.call());
Console.ReadKey();
}
}
Does the compiler add virtual and override automatically at compile time?
I would be pleased if someone would explain to me the reason for using virtual and override.
(note, I'm quietly ignoring the compile errors)
Now do:
BaseClass obj = new DerivedClass();
Console.WriteLine(obj.call());
Without virtual, this will print A, when actually a DerivedClass should be writing B. This is because it has simply called the BaseClass implementation (since obj is typed as BaseClass, and no polymorphism is defined).
Virtual and override are a base mechanism of inheritance in object oriented programming.
This is perhaps the most important thing to understand when you use classes in a language like C# or Java.
http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)
Inheritance allow you to reuse code adding new fields, properties and methods or replacing methods and properties of previously defined classes.
Virtual and Override allow you to replace the content of a method, and when i say replace, i say replace.
I would propose you a nice example.
public class MyClassEnglish
{
public virtual string SomethingToSay()
{
return "Hello!";
}
public void WriteToConsole()
{
Console.WriteLine(this.SomethingToSay());
}
}
public class MyClassItalian :
MyClassEnglish
{
public override string SomethingToSay()
{
return "Ciao!";
}
}
int main()
{
MyClassItalian it = new MyClassItalian();
it.WriteToConsole();
}
If you omit virtual and override, MyClassItalian will print out "Hello!" and not "Ciao!".
In your example you show a Shadowing technique, but the compiler should give you a warning.
You shoul add the "new" keyword if you want to hide a method in a base class.
Hiding a method is not overriding! Is just hiding.
One possible use that comes into my mind is that it can be used when you need some kind of optimization for example.
public abstract class MySpecialListBase
{
public int Count()
{
return this.GetCount();
}
protected abstract int GetCount();
}
public sealed class MySpecialArrayList : MySpecialListBase
{
int count;
public new int Count()
{
return this.count;
}
protected override int GetCount()
{
return this.count;
}
}
Now...
You can use MySpecialListBase in all your code, and when you call the Count() it will call the virtual method GetCount().
But if you use just MySpecialArrayList it will call the optimized Count() that is not virtual and that just return a field, increasing performances.
// This works with all kind of lists, but since it is a more general purpose method it will call the virtual method.
public void MyMethod(MySpecialListBase list)
{
Console.WriteLine(list.Count());
}
// This works only with MySpecialArrayList, and will use the optimized method.
public void MyMethod(MySpecialArrayList list)
{
Console.WriteLine(list.Count());
}
Best example I can think of where this is useful is when you create your own object(class) and you have to add a list of that object to a combobox.
When you add your object to the combobox you want to be able to control what text is displayed for each item. Object.toString is a virtual method. http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx and because of this you can override that method and set .toString to display the correct information about your object by overriding it.
public MyClass()
{
private int ID;
public override string ToString()
{
return "My Item:" + ID;
}
}
Method Overriding:
Where you define or implement a virtual method in a parent class and then replace it in a descendant class.
When you decide to declare a method as virtual, you are giving permission to derived classes to extend and override the method with their own implementation. You can have the extended method call the parent method's code too.
In most OO languages you can also choose to hide a parent method. When you introduce a new implementation of the same named method with the same signature without overriding, you are hiding the parent method.
C# Overriding
In C#, you specify a virtual method with the virtual keyword in a parent class and extend (or replace) it in a descendant class using the override keyword.
Use the base keyword in the descendant method to execute the code in the parent method, i.e. base.SomeMethod().
Syntax Example:
class Robot
{
public virtual void Speak()
{
}
}
class Cyborg:Robot
{
public override void Speak()
{
}
}
Override Details
You cannot override a regular non-virtual method, nor a static method.
The first version of the parent method must be virtual or abstract.
You can override any parent method marked virtual, abstract, or override (already overridden).
The methods must have the same signature.
The methods must have the same visibility (the same access level).
Use the base keyword to refer to the parent class as in base.SomeMethod().
C# Override Example
The following code snippet demonstrates using virtual and override to override a parent method in a descendant class.
using System;
class Dog
{
public virtual void Bark()
{
Console.WriteLine("RUFF!");
}
}
class GermanShepard:Dog
{
public override void Bark()
{
Console.WriteLine("Rrrrooouuff!!");
}
}
class Chiuaua:Dog
{
public override void Bark()
{
Console.WriteLine("ruff");
}
}
class InclusionExample
{
public static void Main()
{
Dog MyDog=new Dog();
MyDog=new GermanShepard();
MyDog.Bark(); // prints Rrrrooouuff!!
MyDog=new Chiuaua();
MyDog.Bark(); // prints ruff;
}
}
Hiding a Method with New
Use the new keyword to introduce a new implementation of a parent method (this hides the parent method). You can hide a method without using new but you will get a compiler warning. Using new will suppress the warning.
The new and override modifiers have different meanings. The new modifier creates a new member with the same name, signature, and visibility and hides the original member. The override modifier extends the implementation for an inherited member and allows you to implement inheritance-based polymorphism.
Avoid Introducing New Members: Sometimes there are clear reasons to introduce a new method with the same name, signature, and visibility of a parent method. In those clear cases, introducing a new member is a powerful feature. However, if you do not have a clear reason, then avoid introducing a new version of a method by naming the new method something unique and appropriate.
class Robot : System.Object
{
public void Speak()
{
MessageBox.Show("Robot says hi");
}
}
class Cyborg : Robot
{
new public void Speak()
{
MessageBox.Show("hi");
}
}
Calling the Base Class Version
A common task In OO is to extend a method by first executing the parent method code and then adding code. Use the base keyword to refer to the parent class as in base.SomeMethod().
class Robot : System.Object
{
public virtual void Speak()
{
MessageBox.Show("Robot says hi");
}
}
class Cyborg : Robot
{
public override void Speak()
{
base.Speak();
MessageBox.Show("hi");
}
}

Is there any other way to implement Overriding (not virtual and override) in C# / .NET?

Could anyone tell me is there any other way a method can be overridden without using virtual/abstract/override in C#/.NET, Please provide me with an example.Please provide with an example...
(what i am thinking is Extension methods am i correct.....)
No, there is no other way. You can hide an existing method with new if the base method is not marked as virtual, however it does not have the same effect (there is no polymorphism - the call will be dispatched based on the variable type, not on the actual object type).
Extension will not work in this case. Objects own properties and methods take precedence. However you can overload a method using extensions.
You can override methods defined in the extensions, by keeping your extensions closer in the namespace to the place where you are going to use it.
Example:
namespace ConsoleApplication2
{
using System;
using ConsoleApplication3;
internal class Program
{
private static void Main(string[] args)
{
ThirdPartyClass t = new ThirdPartyClass();
Console.WriteLine(t.Fun("hh"));
Console.WriteLine(t.Fun(1));
}
}
public static class LocalExtension
{
public static string Fun(this ThirdPartyClass test, int val)
{
return "Local" + val;
}
public static string Fun(this ThirdPartyClass test, string val)
{
return "Local" + val;
}
}
}
namespace ConsoleApplication3
{
public class ThirdPartyClass
{
public virtual string Fun(string val)
{
return "ThirdParty" + val.ToUpper();
}
}
public static class ThripartyExtension
{
public static string Fun(this ThirdPartyClass test, int val)
{
return "ThirdParty" + val;
}
}
}
You can use the "new" keyword on your method to "hide" a method that was not declared as abstract/virtual, however if the method is called from a variable type-casted as the base class, it won't call your new method. This is the similar to overriding.
Example:
public class A
{
public string GetName() { return "A"; }
}
public class B : A
{
// this method overrides the original
public new string GetName() { return "B"; }
}
Extension methods allow you to add new methods to any class even if you don't have their source code or they're sealed. This is not the same as overriding
public sealed class A // this could even be from a dll that you don't have source code to
{
}
public static class AExtensionMethods
{
// when AdditionalMethod gets called, it's as if it's from inside the class, and it
// has a reference to the object it was called from. However, you can't access
// private/protected fields.
public static string AdditionalMethod(this A instance)
{
return "asdf";
}
}
Another option is to use interfaces so that you can have two completely different objects that both have the same method, but when called from a variable type-casted as the interface, it looks similar to overriding.
You could also use a form of Proxy Mocking framework like Microsoft Moles, or CastleWindsor -> They have a way of instantiating a "proxy" object that has the same interface as the real object, but can provide a different implementation for each method.

Inheritence in C# question - is overriding internal methods possible?

Is it possible to override an internal method's behavior?
using System;
class TestClass
{
public string Name { get { return this.ProtectedMethod(); } }
protected string ProtectedMethod()
{
return InternalMethod();
}
string InternalMethod()
{
return "TestClass::InternalMethod()";
}
}
class OverrideClassProgram : TestClass
{ // try to override the internal method ? (doesn't work)
string InternalMethod()
{
return "OverrideClassProgram::InternalMethod()";
}
static int Main(string[] args)
{
// TestClass::InternalMethod()
Console.WriteLine(new TestClass().Name);
// TestClass::InternalMethod() ?? are we just screwed?
Console.WriteLine(new OverrideClassProgram().Name);
return (int)Console.ReadKey().Key;
}
}
I think you've got something confused here. There is an actual keyword "internal", is this what you want?
internal string InternalMethod()
{
return "TestClass::InternalMethod()";
}
But I think what you're really looking for is the "virtual" keyword. This allows you to do an override:
Parent Class
protected virtual string InternalMethod()
{
return "TestClass::InternalMethod()";
}
Child Class
protected override string InternalMethod()
{
return "TestProgram::InternalMethod()";
}
Using the "new" keyword is valid, but it completely reimplements the method. I.e. it breaks polymorphism.
Edit:
Here's a link.
In Java everything is virtual unless it is static/final. In C# you have to explicitly declare an instance method as virtual and then that method cannot be private. This article explains why.
By default all members of a class are private, so if you do not provide an access modifier (other than private of course) the InternalMethod() method in your example is private and cannot be virtual and thus cannot be overridden.
You must change it's access modifier and mark it as virtual and in the child class you must override it for the code to work the way you want it too.
This may not answer your question, but just to add a cent.
Internal denotes that types or members are accessible only within files in the same assembly. They are public to the assembly but having access slightly less than the public in actual.
MSDN Access Modifiers,
A common use of internal access is in
component-based development because it
enables a group of components to
cooperate in a private manner without
being exposed to the rest of the
application code. For example, a
framework for building graphical user
interfaces could provide Control and
Form classes that cooperate using
members with internal access. Since
these members are internal, they are
not exposed to code that is using the
framework
Try using the override keyword ... the new keyword is to call a class constuctor
Sure, it's possible, but in order to override a method, the method needs to be virtual or abstract, same as any other visibility.
class Base
{
internal virtual void Foo()
{
Console.WriteLine("Foo from Base");
}
}
class Derived : Base
{
internal override void Foo()
{
Console.WriteLine("Foo from Derived");
}
}
When you use the new keyword, it's called method hiding, which is not the same thing. If I write this:
class Base
{
internal void Foo()
{
Console.WriteLine("Foo from Base");
}
}
class Derived : Base
{
internal new void Foo()
{
Console.WriteLine("Foo from Derived");
}
}
static void Main()
{
Base b = new Derived();
b.Foo();
}
Then it will execute the Base Foo method, not Derived. In other words it will print Foo from Base. In the first case, it would still have executed the Derived method and printed Foo from Derived.

Why does C# take value from overridden property instead of the overriding property?

I would suspect the code below to output:
(I am a SmartForm object and using the method in SmartForm).xml
instead, however, it outputs:
(I am a SmartForm object and using the method in Item).xml
Why is that? How can I force C# to take the value from the overriding property? That is why I am overriding the property.
using System;
namespace TestInhersdk234
{
public class Program
{
static void Main(string[] args)
{
SmartForm smartForm = new SmartForm();
Console.ReadLine();
}
}
public class SmartForm : Item
{
public SmartForm()
{
Console.WriteLine(FullXmlDataStorePathAndFileName);
}
public new string GetItemTypeIdCode
{
get
{
return String.Format("(I am a {0} object and using the method in SmartForm)", this.GetType().Name);
}
}
}
public class Item
{
public string FullXmlDataStorePathAndFileName
{
get
{
return GetItemTypeIdCode + ".xml";
}
}
public string GetItemTypeIdCode
{
get
{
return String.Format("(I am a {0} object and using the method in Item)", this.GetType().Name);
}
}
}
}
You're not actually overriding. You're hiding. To override:
class MyBase
{
public virtual void foo() {}
}
class MyClass : MyBase
{
public override void foo() {}
}
You need to add the override keyword to the overriding method?
Item's properties which you wish to override are not marked virtual. As a result, when you redefine them in SmartForm, you are merely "hiding" them, and not actually overriding them. (Additionally, you will need the override keyword in SmartForm as well.)
Check out this guide.
GetItemTypeIdCode isn't virtual; you're not overriding it, you're just hiding it. In that case, which method gets executed isn't based on the dynamic type of the object, but on the static type of the object reference. Inside FullXmlDataStorePathAndFileName, the static type of 'this' is Item, not SmartForm, so the Item implementation of GetItemTypeIdCode is called.
the property in the base class should be marked virtual
also the property in the inherited class should be marked overrides
also i am not sure why the keyword new appears in your code in the property definition

Categories

Resources