As far as i see in c#,
virtual function are not just for polymorphism,
it is also for overriding the hiding method warning by the compiler
am i right ?
i will give an example :
class A
{
public void func(int a)
{
....
}
}
class B:A
{
public void func(int a)
{
....
}
}
now , im using B x = new B();
so the compiler will warn me for method in class B hides the one in A.
so there is 2 solutions :
1) mark the one in B with the New keyword
2) make the one in 'A' virtual and the one in B - Overriding – this will clear the warning of hiding..
the only difference will be with Polymorphism A x = new B();
if there will be ‘new’ in class B – always the one from A will be called while if im using the virtual and not the new mechanism – the one from B will be called.
so virtual has 2 roles in .net : (please correct me if im wrong)
1) resolve the hiding warning (in non-Polymorphism enviroment)
2) and of course overriding the functions in yes-polymorphism enviroment.
please correct me if im wrong.
No, virtual methods are for polymorphism. Your “solution” #2 will change the behaviour of calling
x.func()from calling the A implementation to calling the B implementation – i.e. making it polymorphic. Yes, it removes the warning – but it’s no longer a “non-polymorphism environment” as you’ve made the behaviour polymorphic. Did you want to do that, or not? If you did, thenvirtualandoverrideis the way to go. If you didn’t, you should usenewor rename the method.I would strongly advise you to avoid using method hiding unless you really need to. Do you even need
Bto derive fromA? If you want to give it another method with the same name but a different meaning, consider making them separate classes. Personally I steer away from inheritance unless there’s a clear polymorphic relationship.(Note that overriding and overloading are different concepts, by the way. You mean overriding here.)