Click here to Skip to main content
15,913,587 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
using System;

public class Base
{
    public Base()
    {
    }

    void M1()
    {
    }

    void M2()
    {
    }  
}

public class Derived : Base
{
    //this class should get only method m1
}

The requirement is : the base class contains the 2 methods M1, M2
The derived class should be inherit only M1 and not M2.
For this what should I change in my Base class?

How can this be done?

Regards,
Siddheshwar Duchal

[Edit]Code block added & C# tag added[/Edit]
Posted
Updated 31-Oct-12 6:20am
v3

If you do it like in your code block, then M1 and M2 will not be derived, because they are private. Keep M2 private, but make M1 public:
C#
using System;
 
public class Base
{
    public Base()
    {
    }
    public void M1()
    {
    }
    void M2()
    {
    }  
}
 
public class Derived : Base
{
    //now this class get only method m1
}


Hope this helps.
 
Share this answer
 
Comments
bbirajdar 31-Oct-12 6:36am    
Can M1 be made 'protected' and still be inherited instead of making it public?
Thomas Daniels 31-Oct-12 6:37am    
Yes, you can.
Siddheshwar Duchal from Pune 31-Oct-12 8:25am    
Yes, It will Inherited logically, But can't access it. (when M1 be made as Private/Protected)
I'm right?
Thomas Daniels 31-Oct-12 8:28am    
If the method is private, the method will not be inherited. If the method is protected, the method will be inherited, but isn't visible for another class, and if the method is public, the method will be inherited and is visible for all classes.
Siddheshwar Duchal from Pune 31-Oct-12 8:59am    
Right.
I got answer of my all question.
Many thanks.
You can't change the visibility of methods when you inherit them - even if you create a new private method to "hide" it, the base method will still be available.
However, you can prevent it being seen easily:
C#
public class C1
    {
    public void M1() { Console.WriteLine("C1:M1"); }
    public void M2() { Console.WriteLine("C1:M2"); }
    }
public class C2 : C1
    {
    [Browsable(false),
    EditorBrowsable(EditorBrowsableState.Never)]
    public new void M1() { Console.WriteLine("C2:M1"); }
    }

This will hide it from intellisense so neither version (C1 or C2) is visible - but only from outside the assembly. It will still be possible to call the C2 version directly by typing in the name, but you won't be able to access the C1 version via a C2 variable.
I.e. If you add a reference to your control library within an different solution, Intellisense will not list the property. (You can however still access it if you type the name in fully. Irritating, but true.)
 
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