Link to home
Start Free TrialLog in
Avatar of HOVE
HOVE

asked on

How to hide method so you can't access?

I want to hide a method so that it is not accessible from an outside of the class.
public class MyList : List<object>
{
	//optional method
	public new void Insert( int index, object item )
	{
	}
}
 
public class MyClass
{
	public MyClass()
	{
		MyList ml = new MyList();
 
		//I want Insert to be hidden, so I can't access it
		//ml.Insert();
	}
}

Open in new window

Avatar of RishadanPort
RishadanPort

declare the method as private.
If though you are overriding a method, the method must be declared as public.  To overcome this, you can put another wrapper class around the current class, and label the inner class as private

Example:
//Shell class has access to the MyList class. Doing this will hide the Insert method from non Shell objects
public class Shell{
   private class MyList : List<object>
   {
	   //optional method
	   public new void Insert( int index, object item )
	   {
   	   }
   }
}

Open in new window

Avatar of HOVE

ASKER

Declaring method as private does not solve the problem, base Insert is still accessible.

public class Shell{
   private class MyList : List<object>
   {
      //define all hidden methods here
   }
 
   private MyList list;
 
   public Shell(){
      list = new MyList();
   }
 
   //Define public methods here that the user can use. Do not
   //show the MyList class
}

Open in new window

In the example above the Shell class will have access to the list variable, that is a MyList. However, when you initialize the Shell class, you cannot however use the Insert function, since the MyList class is hidden
ASKER CERTIFIED SOLUTION
Avatar of RishadanPort
RishadanPort

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of HOVE

ASKER

Is there no other way, maybe with an attribute, to hide a method? Now I need to call Shell.List to access methods, otherwise I need to specify all methods in Shell class if I what them to bee accessed directly.
That's a good question. I have come across this type of thing, but I don't no of another way around it. I will put something up if I figure something out