How can I adapt a c# class with private methods? - c#

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.

Related

C# When a class instance is created to execute a method within the class

public class TestClass
{
private void Method1() {...}
}
Is it possible to execute method1 as soons as i initialize the class?
If so, How do I do it?
I didn't know how to phrase my question, so my apologies if there is already a similar question
Yes, from the constructor:
public class TestClass
{
public TestClass()
{
// initialize here...
// then call your method:
Method1();
}
private void Method1() {...}
}
If this method takes a long time to execute, it is not appropriate for the constructor because the caller might not expect this. Then you should make your method public(with a meaningful name) and let it be called afterwards. Constructors are supposed to initialize objects not use them.
So to create the class you will be using code similar to this right?
var testClassInstance = new TestClass()
That being the case, all you need to do is put the call to the method in the constructor of TestClass Like So:
public class TestClass
{
public TestClass(){
Method1();
}
private void Method1() {...}
}

C#: Giving access to private members without 3-fold code duplication

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();
}
}
}

Private class with Public method?

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.

C# - Class design & access modifiers

Given the following:
public abstract class Base
{
// other stuff
public static void StaticMethod()
{
PrivateMethod();
}
// here should be PrivateMethod() declaration somehow
}
public sealed class Derived: Base
{
// other stuff
public void InstanceMethod()
{
// call somehow PrivateMethod
PrivateMethod();
}
}
I need to make use of PrivateMethod() from 2 different contexts (different assemblies). Once calling Base.StaticMethod(), and the second time by using an instance of the Derived class d.InstanceMethod();.
I am looking for a way how to design PrivateMethod() inside the Base class. Of course PrivateMethod() should not be visible outside the Base and Derived classes.
I was thinking something about "protected static PrivateMethod() {}" but I read I should not do that...
What do you recommend guys?
protected static void PrivateMethod() {}
Is OK (apart form the name) and does what you require. You won't need base. when calling it from Derived.
I had never heard this before, so I went looking for something that said what you described. I found this article: New Design Guideline: Avoid Protected Static. However, it only talks about protected static field.
I don't think the article actually makes a good case for what it is trying to say. Rather than just describing how protected statics can lead to complications, it uses a very simple example of the base class designer not setting the right access flags for something that should not be accessed by everyone.
That being said, there is still a point that protected static can lead to complications. Protected static means that any subclass can call a method at any time. This can lead to thread safety concerns if the method is written naively. It seems like the article was written in a way that it conveys "Don't do it" rather than "If you need to do it, be careful."
You could just call the public StaticMethod() from your derived class's InstanceMethod() ... since it indirects back to PrivateMethod() anyway. That way you can leave PrivateMethod() private. The implementation would be something like:
public abstract class Base
{
// other stuff
public static void StaticMethod()
{
PrivateMethod();
}
// here should be PrivateMethod() declaration somehow
private static void PrivateMethod()
{
// do stuff
}
}
public sealed class Derived: Base
{
// other stuff
public void InstanceMethod()
{
// call somehow PrivateMethod
StaticMethod();
}
}
PS: If there is need during StaticMethod to differentiate between a public caller or a derived class caller (from InstanceMethod) it could be either passed as parameter, or determined via reflection.

What's the difference between an abstract class, and a class with only protected constructors? (.NET)

What are all the difference between an abstract class, and a class with only protected constructor(s)? They seem to be pretty similar to me, in that you can't instantiate either one.
EDIT:
How would you create an instance in a derived class, with a base class with a protected constructor? For instance:
public class ProtectedConstructor
{
protected ProtectedConstructor()
{
}
public static ProtectedConstructor GetInstance()
{
return new ProtectedConstructor(); // this is fine
}
}
public class DerivedClass : ProtectedConstructor
{
public void createInstance()
{
ProtectedConstructor p = new ProtectedConstructor(); // doesn't compile
}
public static ProtectedConstructor getInstance()
{
return new ProtectedConstructor(); // doesn't compile
}
}
You can instantiate a class with protected constructors from within the class itself - in a static constructor or static method. This can be used to implement a singleton, or a factory-type thing.
An abstract class cannot be instantiated at all - the intent is that one or more child classes will complete the implementation, and those classes will get instantiated
Edit:
if you call ProtectedConstructor.GetInstance(); instead of new ProtectedConstructor();, it works. Maybe protected constructors can't be called this way? But protected methods certainly can.
Here is an interesting article on the topic.
Most of the time, there is little practical difference, as both are only able to be generated via a subclass.
However, marking a class abstract has two benefits:
With protected constructors, it's still possible to create an instance of the class in two ways. You can use Activator.CreateInstance with BindingFlags.NonPublic, or you can use a factory method defined in the class (or a subclass) to create an instance of the class. A class marked abstract, however, cannot be created.
You are making your intention more clear by marking the class abstract. Personally, I find this the most compelling reason to do so.
From an outside , black-box perspective, yes they are similar in that you cannot instantiate either one. However, you can never instantiate an abstract class, where you can construct a class with only protected constructors from within the class itself, or from an inheritor.
An abstract class can have abstract methods; methods that consist only of the method signature, but no body, that child classes must implement.
Seriously, not one person mentioned that yet?
Your example is flawed because in the getInstance case because you construct a ProtectedConstructor class and expect to down cast it as a DerivedClass. Instead you need a slightly more complete implementation where the derived class has a constrcutor:
public class ProtectedConstructor
{
protected ProtectedConstructor(string arg)
{
// do something with arg
}
public static ProtectedConstructor GetInstance()
{
return new ProtectedConstructor("test");
}
}
public class DerivedClass : ProtectedConstructor
{
protected DerivedClass(string arg) : base(arg)
{
}
public void createInstance()
{
DerivedClass p = new DerivedClass("test");
}
public static DerivedClass getInstance()
{
return new DerivedClass("test");
}
}
Regardless the major difference usage of abstract classes is to define abstract methods that subclasses must implement but you don't want to provide a default implementation for. For example suppose you have some kind of Thread class that has a Run method. You want to ensure that every call to Run first setups up some logging then does the real work of the thread and then stops logging. You could write an abstract Thread class like this:
public abstract Thread
{
protected Thread()
{
}
public void Run()
{
LogStart();
DoRun();
LogEnd();
}
protected abstract DoRun();
private void LogStart()
{
Console.Write("Starting Thread Run");
}
private void LogEnd()
{
Console.Write("Ending Thread Run");
}
}
public class HelloWorldThread : Thread
{
public HelloWorldThread()
{
}
protected override DoRun()
{
Console.Write("Hello World");
}
}
Another thing to consider, that I didn't see other people mention, is that your code may be maintained in the future. If the maintainer adds a public constructor to a class, then it can be instantiated. This might break your design, so you should prevent it (or design to accommodate it).
To prevent other people from making these kinds of changes, you can comment your code. Or, as other people said, use "abstract" to explicitly document your intent.
Well, the first difference that comes to mind is that an abstract class can not be instantiated, but a class with protected constructors could be instantiated throw another public method.
A common example of this might be something like the Singleton pattern: http://en.wikipedia.org/wiki/Singleton_pattern
if you inherit an abstract class from another abstract class, you do not have to satisfy abstract methods, but you do with a normal class with protected ctors. Examples
public abstract class Parent
{
protected abstract void AMethod();
}
public abstract class Child: Parent
{
// does not implement AMethod, and that's ok
}
public class Child2: Parent
{
// does not implement AMethod, and that will cause a compile error
}
If your intent is to only allow static uses of the class (i.e. not to use it as a pure base class) then you should use the static keyword instead; the CLR will prevent instances of the class being created via any method including Reflection (AFAIK).

Categories

Resources