How to hide functions within classes in c#?

1k views Asked by At

I need to hide few methods inside a class based on the parameter that is passed to the constructor in c#. How would I do this? Thanks in advance!

More Info: I was part of this GUI development where they had a API with access to registers in a hardware. Now they are releasing a newer hardware so I need to support both old and new one which has a newer API(Mostly duplicate of old one with some old removed and some new registers added).

Moreover, I need to keep this only one class called "API" as we used it in many places. So the idea of using a newer API with a different name was ruled out.

Now finally, I got this idea of including the newer one into old one with just conditionally hiding the registry access methods.

5

There are 5 answers

5
Keith Nicholas On

You can't toggle the visibility of members..... the best bet is to have different interfaces that hide the members.

public interface IName
{
   string Name { get; set; }
}


public interface INumber
{
   string PhoneNumber { get; set; }
}


public class Worker : IName, INumber
{
    public string Name { get; set; }
    public string PhoneNumber { get; set; }
}

So either use Worker through the IName or the INumber interface and it will hide the other members on the class....

0
Matt On

I think you might be looking at a re-factor here. Try making a base class with all the methods / properties that behave the same regardless of the parameter, then two child classes which behave differently. Also have a look at the class factory pattern.

0
Jerod Houghtelling On

You will need to restructure the code into multiple classes or interfaces. You can't dynamically change the visibility level of class members based on a parameter value. Members are construction time information not run time.

0
Sergey Gavruk On

You can't change visibility of methods, but you can pass parameter to the single method and do some logic depending on your parameter by using switch - case. But it depends on your method structure.
Try to review your class and change its design. Maybe you can find any design pattern that will help you.

0
Sergey Kudriavtsev On

You may actually do something alike using Dynamic code generation, although this is more like a hack than actual code that should be used in production.

Maybe if you explain why you need this then you may get more relevant answers.