I have a class
public class Foo{
public Foo{...}
private void someFunction(){...}
...
private Acessor{
new Acessor
}
}
with some private functionality (someFunction). However, sometimes, I want to allow another class to call Foo.SomeFunction, so I have an inner class access Foo and pass out that:
public class Foo{
public Foo{...}
private void someFunction(){...}
...
public Acessor{
Foo _myFoo;
new Acessor(Foo foo){_myFoo = foo;}
public void someFunction(){
_myFoo.someFunction();
}
}
}
With this code, if I want a Foo to give someone else pemission to call someFunction, Foo can pass out a new Foo.Accessor(this).
Unfortunately, this code allows anyone to create a Foo.Accessor initiated with a Foo, and they can access someFunction! We don't want that. However, if we make Foo.Accessor private, then we can't pass it out of Foo.
My solution right now is to make Acessor a private class and let it implement a public interface IFooAccessor; then, I pass out the Foo.Accessor as an IFooAccessor. This works, but it means that I have to declaration every method that Foo.Accessor uses an extra time in IFooAccessor. Therefore, if I want to refactor the signature of this method (for example, by having someFunction take a parameter), I would need to introduce changes in three places. I've had to do this several times, and it is starting to really bother me. Is there a better way?
If someFunction has to be accessible for classes in the same assembly, use internal instead of private modifier.
http://msdn.microsoft.com/en-us/library/7c5ka91b(v=vs.71).aspx
If it has to be accessible for classes which are not in the same assemble then, it should be public. But, if it will be used by just a few classes in other assemblies, you probably should think better how you are organizing you code.
It's difficult to answer this question, since it's not clear (to me at least) what exactly you want to achieve. (You write make it difficult for someone to inadverdantly use this code in a comment).
Maybe, if the method is to be used in a special context only, then explicitly implementing an interface might be what you want:
public interface ISomeContract {
void someFunction();
}
public class Foo : ISomeContract {
public Foo() {...}
void ISomeContract.someFunction() {...}
}
This would mean, that a client of that class would have to cast it to ISomeContract to call someFunction():
var foo = new Foo();
var x = foo as ISomeContract;
x.someFunction();
I had a similar problem. A class that was simple, elegant and easy to understand, except for one ugly method that had to be called in one layer, that was not supposed to be called further down the food chain. Especially not by the consumers of this class.
What I ended up doing was to create an extension on my base class in a separate namespace that the normal callers of my classes would not be using. As my method needed private access this was combined with explicit interface implementation shown by M4N.
namespace MyProject.Whatever
{
internal interface IHidden
{
void Manipulate();
}
internal class MyClass : IHidden
{
private string privateMember = "World!";
public void SayHello()
{
Console.WriteLine("Hello " + privateMember);
}
void IHidden.Manipulate()
{
privateMember = "Universe!";
}
}
}
namespace MyProject.Whatever.Manipulatable
{
static class MyClassExtension
{
public static void Manipulate(this MyClass instance)
{
((IHidden)instance).Manipulate();
}
}
}
Related
I have a scenario that (simplified) is as follows:
public static class Example
{
public const int CONSTANT_VALUE = 1;
public static Example<T> Create<T>(IEnumerable<T> argument)
where T : class
{
return new Example<T>(argument);
}
//More overloads of Create<T>, possibly other static methods, etc..
}
public class Example<T>
where T : class
{
public Example(IEnumerable<T> argument)
{
//Do Stuff
//Nothing like this in the real code, just example
//that constants are used from the other class.
if (something == Example.CONSTANT_VALUE)
{
//Do A Thing
}
}
//Lots more code
}
The basic idea is that I can have static methods, constants, etc. available through the name of the class through the static class, while the actual implementation is in the type-argumented non-static class.
My question is whether or not this is a good way to set this up. Is there a way to put some static methods and constants that don't care what the type argument is on Example<T>? Is there otherwise a more recommended pattern? What I have works fine, but I wanted to know if there are other ways since this is the first time I've ended up doing something like this (not that it's conceptually new to me, just never had need).
This would only make sense if the constants are public. If they are only for internal use inside Example<T> then this is pointless, becuase you can reference them without a fully qualified name.
If the constants are of public use, I wouldn't use this pattern anayways; Example and Example<T> are two different classes, it is potentially confusing to any user, and not immeadiately obvious, that constants defined in the non generic class are aplicable to the generic one.
You are only avoding the user a few keystrokes, I'm not really sure it is worth it.
Update: other options
In this scenario, I'd use the following factory pattern (assuming the users are outside your assembly)
public class Example<T>
{
internal Example() { } //disallow users from instantiating this class
...
}
public static class Example
{
public const int Constant = ...
public static Example<T> Create<T>() { return new ... }
}
And now all users will interact only with Example and avoid using Example<T>. You could even enforce this with users of your own assembly, you'd just need to make Example<T> a private nested class implementing a public interface:
public interface IExample<T>
{
...
}
public static class Example
{
private class Example<T>: IExample<T> { ... }
public static IExample<T> Create<T>() { ... }
....
}
Unless there is a reason this wouldn't work in your case, I would prefer to use a non-static base class Example, and then let Example<T> inherit from this class. That way you get direct access to all the methods in Example, without having to qualify with the name. Of course, this assumes that the Example class is exclusively to be used in connection with the various typed classes Example<T>.
Is there any use of declaring a static class as private.Here is the code below:
static class DerivedClass
{
private static string GetVal()
{
return "Hello";
}
}
The sample code you provided actually illustrates an internal class, not a private class. This is perfectly fine and is done all the time. It means the methods of the class are available from other classes within the same module, but not externally.
If you mean declaring private members of static classes, sure there is.
static class DerivedClass
{
public static string GetVal()
{
return GetValInternal();
}
private static string GetValInternal()
{
return "Hello";
}
}
If you mean declaring a private static nested classes (because only nested classes can be private, according to the documentation), then you can do it, but there's probably no reason to do it.
class SomeClass
{
private static class DerivedClass
{
public static string GetVal()
{
return "Hello";
}
}
}
Is equivalent to
class SomeClass
{
private static string GetVal()
{
return "Hello";
}
}
By default classes with no access modifiers like in your example are internal, not private. See this reference: http://msdn.microsoft.com/en-us/library/ms173121.aspx. This means that you can access this class from anywhere inside the library/project. This makes sense because it allows you to use the class internally without necessarily exposing it to the outside world.
Explicitly declaring it as private however makes sense in some rare cases only in my opinion. I have used it before for nested classes simply to group certain things together and make my code prettier/more readable. However I find that if I am creating nested classes it usually means that I need to redesign my code and pull some of it into separate files and separate classes. Rather try to stick to one class per file.
Here is a piece of code:
private class myClass
{
public static void Main()
{
}
}
'or'
private class myClass
{
public void method()
{
}
}
I know, first one will not work. And second one will.
But why first is not working? Is there any specific reason for it?
Actually looking for a solution in this perspective, thats why made it bold. Sorry
It would be meaningful in this scenario; you have a public class SomeClass, inside which you want to encapsulate some functionality that is only relevant to SomeClass. You could do this by declaring a private class (SomePrivateClass in my example) within SomeClass, as shown below.
public class SomeClass
{
private class SomePrivateClass
{
public void DoSomething()
{
}
}
// Only SomeClass has access to SomePrivateClass,
// and can access its public methods, properties etc
}
This holds true regardless of whether SomePrivateClass is static, or contains public static methods.
I would call this a nested class, and it is explored in another StackOverflow thread.
Richard Ev gave a use case of access inside a nested classes. Another use case for nested classes is private implementation of a public interface:
public class MySpecialCollection<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{
return new MySpecialEnumerator(...);
}
private class MySpecialEnumerator : IEnumerator<T>
{
public bool MoveNext() { ... }
public T Current
{
get { return ...; }
}
// etc...
}
}
This allows one to provide a private (or protected or internal) implementation of a public interface or base class. The consumer need not know nor care about the concrete implementation. This can also be done without nested classes by having the MySpecialEnumerator class be internal, as you cannot have non-nested private classes.
The BCL uses non-public implementations extensively. For example, objects returned by LINQ operators are non-public classes that implement IEnumerable<T>.
This code is syntactically correct. But the big question is: is it useful, or at least usable in the context where you want to use it? Probably not, since the Main method must be in a public class.
Main() method is where application execution begin, so the reason you cannot compile your first class (with public static void Main()) is because you already have Main method somewhere else in your application. The compiler don't know where to begin execute your application.
Your application must have only one Main method to compile with default behavior otherwise you need to add /main option when you compile it.
I would like to adapt a class with a private method, so that the adapter calls this private method:
Consider this class
public class Foo
{
private void bar()
}
I would like a class that follows the command pattern, and calls bar() in it's execute method:
public class FooCommand
{
private Foo foo_;
public FooCommand(Foo foo)
{
foo_ = foo;
}
public void execute()
{
foo.bar();
}
}
Any ideas would be greatly appreciated.
Thanks!
I believe there are many options:
Instead of a FooCommand, use an interface ICommand with an Execute method. Then declare Foo in such a way that it implements ICommand:
public class Foo : ICommand {
private void bar() { ... }
void ICommand.Execute() { bar(); }
}
I believe this is the most attractive solution: the method can still be private; you don’t need to instantiate an extra FooCommand for every Foo; and you don’t need to declare a separate XCommand class for every X class that wants it.
Declare the FooCommand class inside the Foo class so that it becomes a nested class. Then the FooCommand can access the private method.
Declare the bar method public or internal.
Declare the bar method protected or protected internal and then derive FooCommand from Foo.
Use Reflection to invoke the private method (use Type.GetMethod followed by MethodBase.Invoke). I believe most developers would consider this a dirty hack.
You would need to at least make bar() protected rather than private. Private functions can only be called by the class that declares them, unless you decide to use Reflection which then places security requirements on your application.
The only way to do this would be to use reflection and invoke the method that way, however I would strongly suggest against doing that. Why not just make the method internal?
public void execute()
{
var m = foo_.GetType().GetMethod("bar", BindingFlags.NonPublic|BindingFlags.Instance);
m.Invoke(foo_, null);
}
I agree with the other posters who say make the method internal and use InternalsVisibleToAttribute if needed.
Do you have access to class Foo as in access to modify the class? If not, I don't believe you can call its private method bar() from another class.
What is the best way to implement polymorphic behavior in classes that I can't modify? I currently have some code like:
if(obj is ClassA) {
// ...
} else if(obj is ClassB) {
// ...
} else if ...
The obvious answer is to add a virtual method to the base class, but unfortunately the code is in a different assembly and I can't modify it. Is there a better way to handle this than the ugly and slow code above?
Hmmm... seems more suited to Adapter.
public interface ITheInterfaceYouNeed
{
void DoWhatYouWant();
}
public class MyA : ITheInterfaceYouNeed
{
protected ClassA _actualA;
public MyA( ClassA actualA )
{
_actualA = actualA;
}
public void DoWhatYouWant()
{
_actualA.DoWhatADoes();
}
}
public class MyB : ITheInterfaceYouNeed
{
protected ClassB _actualB;
public MyB( ClassB actualB )
{
_actualB = actualB;
}
public void DoWhatYouWant()
{
_actualB.DoWhatBDoes();
}
}
Seems like a lot of code, but it will make the client code a lot closer to what you want. Plus it'll give you a chance to think about what interface you're actually using.
Check out the Visitor pattern. This lets you come close to adding virtual methods to a class without changing the class. You need to use an extension method with a dynamic cast if the base class you're working with doesn't have a Visit method. Here's some sample code:
public class Main
{
public static void Example()
{
Base a = new GirlChild();
var v = new Visitor();
a.Visit(v);
}
}
static class Ext
{
public static void Visit(this object b, Visitor v)
{
((dynamic)v).Visit((dynamic)b);
}
}
public class Visitor
{
public void Visit(Base b)
{
throw new NotImplementedException();
}
public void Visit(BoyChild b)
{
Console.WriteLine("It's a boy!");
}
public void Visit(GirlChild g)
{
Console.WriteLine("It's a girl!");
}
}
//Below this line are the classes you don't have to change.
public class Base
{
}
public class BoyChild : Base
{
}
public class GirlChild : Base
{
}
I would say that the standard approach here is to wrap the class you want to "inherit" as a protected instance variable and then emulate all the non-private members (method/properties/events/etc.) of the wrapped class in your container class. You can then mark this class and its appropiate members as virtual so that you can use standard polymorphism features with it.
Here's an example of what I mean. ClosedClass is the class contained in the assembly whose code to which you have no access.
public virtual class WrapperClass : IClosedClassInterface1, IClosedClassInterface2
{
protected ClosedClass object;
public ClosedClass()
{
object = new ClosedClass();
}
public void Method1()
{
object.Method1();
}
public void Method2()
{
object.Method2();
}
}
If whatever assembly you are referencing were designed well, then all the types/members that you might ever want to access would be marked appropiately (abstract, virtual, sealed), but indeed this is unfortunately not the case (sometimes you can even experienced this issue with the Base Class Library). In my opinion, the wrapper class is the way to go here. It does have its benefits (even when the class from which you want to derive is inheritable), namely removing/changing the modifier of methods you don't want the user of your class to have access to. The ReadOnlyCollection<T> in the BCL is a pretty good example of this.
Take a look at the Decorator pattern. Noldorin actually explained it without giving the name of the pattern.
Decorator is the way of extending behavior without inheriting. The only thing I would change in Noldorin's code is the fact that the constructor should receive an instance of the object you are decorating.
Extension methods provide an easy way to add additional method signatures to existing classes. This requires the 3.5 framework.
Create a static utility class and add something like this:
public static void DoSomething(this ClassA obj, int param1, string param2)
{
//do something
}
Add a reference to the utility class on the page, and this method will appear as a member of ClassA. You can overload existing methods or create new ones this way.