Results 1 to 3 of 3

Thread: [2.0] Access Modifier

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Mar 2006
    Location
    Pennsylvania
    Posts
    1,069

    [2.0] Access Modifier

    Is there an access modifier that makes a method public in the superclass and not existent in its subclass? Sort of like a mix of private and protected. I tried hiding the method in the subclass using the new keyword, but since there are overloads of the same method in the superclass, it only hides one of the overloads, which is not what I need.

    Thanks

  2. #2

    Thread Starter
    Frenzied Member
    Join Date
    Mar 2006
    Location
    Pennsylvania
    Posts
    1,069

    Re: [2.0] Access Modifier

    Actually, I have just modified the design of my code so this isn't really needed, but it would still be nice to know.

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,302

    Re: [2.0] Access Modifier

    There's no way to do that. All you can do is override/shadow the base implementation and either throw an exception or just leave the body empty.

    It should be noted, though, that overriding follows the object while shadowing follows the type. That means that if you override a member in a derived class then cast an instance as the base type, it will still be the derived implementation of the member that gets invoked. If you shadow a member, on the other hand, casting as the base type gives access to the base implementation of the member shadowed in the derived type. Try this to see what I mean:
    CSharp Code:
    1. public class BaseClass
    2. {
    3.     public virtual void Method1()
    4.     {
    5.         MessageBox.Show("BaseClass", "Method1");
    6.     }
    7.  
    8.     public void Method2()
    9.     {
    10.         MessageBox.Show("BaseClass", "Method2");
    11.     }
    12. }
    13.  
    14.  
    15. public class DerivedClass : BaseClass
    16. {
    17.     public override void Method1()
    18.     {
    19.         MessageBox.Show("DerivedClass", "Method1");
    20.     }
    21.  
    22.     public new void Method2()
    23.     {
    24.         MessageBox.Show("DerivedClass", "Method2");
    25.     }
    26. }
    CSharp Code:
    1. BaseClass b1 = new BaseClass();
    2.  
    3. b1.Method1();
    4. b1.Method2();
    5.  
    6. DerivedClass d = new DerivedClass();
    7.  
    8. d.Method1();
    9. d.Method2();
    10.  
    11. BaseClass b2 = (BaseClass)d;
    12.  
    13. b2.Method1();
    14. b2.Method2();

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width