Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
1. Why I am not able to access S class method.
2. And why am I able to create the method with the same name in class M

C#
public class S
     {
         public S()
         {
         }

         public int myFunc(int a, int b)
        {
             return a + b;
         }
     }

    public class M:S
    {
         public M()
         {
         }

        public string myFunc(int a, int b)
         {
             return (a + b).ToString();
        }
     }
 public class Test
 {
     public static void Main(string[] args)
     {
          M mm = new M();
          mm.myFunc(1,2);   // Why I am not able to access S class myFunc
     }
 }
Posted
Comments
Krunal Rohit 26-Feb-14 8:07am    
what error are you getting ?
-KR

Quote:
1. Why I am not able to access S class method.
You actually can.
Since, by the very inheritance concept, M is S, you may call it.
However, M::myFunc hides S::myFunc, so you need a workaround, e.g.:
C#
int k = (mm as S).myFunc(1,2); 


Quote:
2. And why am I able to create the method with the same name in class M
Because the compiler (reluctantly :-) ) allows that. However, if shadowing the method is really your intention, then you'd better inform (as already suggested) the compiler itself using new.
 
Share this answer
 
Comments
Faisalabadians 26-Feb-14 9:03am    
+5better explanation then my answer
CPallini 26-Feb-14 9:04am    
Thank you (and have my 5).
first of all you must use "new" keyword when you have method with same signature in both parent and child classes. you are not able to access S myFucntion because when you instantiate an object like
C#
M mm = new M();

that's mean you are pointing to M class, if the method with same signature is available in both parent and child classes then it depends on which object you are creating? change your code to
C#
S mm = new S(); 

and you will be able to call s myFunc.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900