Exclusive contracting between two classes or interfaces - c#

I'm wondering if it's possible to define a method or property that only specified classes can interact with or see.
For example:
class Thing
{
protected int i;
public virtual int I
{
get
{
return i;
}
}
}
class OtherThing
{
public virtual void ChangeI(Thing thing, int i)
{
thing.i = i;
}
}
Here, I want OtherThing to be able to access i, or a protected set method for I in Thing, despite being defined outside the scope of Thing.
I recognize that I could simply declare OtherThing inside the scope of Thing, which would then have permission to access protected items, however I would also like this to work with interfaces, whose implementations cannot be defined within the scope of the original interface, and who can't declare protected methods anyway.
This may not strictly be possible, but I'd love to hear of similar ways to achieve the same thing, just so I can do some experimentation on my own.
Thanks in advance.

When I read the question it feels pretty much like a Visitor pattern:
http://www.dofactory.com/net/visitor-design-pattern
Let's say that you have a visitor:
class Program
{
static void Main(string[] args)
{
var thing = new Thing();
var otherThing = new OtherThing();
thing.Accept(otherThing);
Console.WriteLine(thing.I);
Console.Read();
}
}
class OtherThing
{
public void Change(Action<int> setI)
{
setI(42);
}
}
class Thing
{
private int i;
public int I { get { return i; } }
public void Accept(OtherThing visitor)
{
visitor.Change(SetI);
}
private void SetI(int i)
{
this.i = i;
}
}
So the idea is: when you accept the visitor you give it a delegate which can change your private field.
I don't really understand the reason, so my example is very artificial. Anyway you can add interfaces to abstract the things, even use some kind of command to pass instead of an Action. But the idea will stay the same.

You are probably looking for the friend-class concept from C++ in C#. C# does not have such a feature on a class-level, so you need to find another design alternative.

Related

Why can a class implement its own private nested interface in C#?

The following code is a valid C# construct that compile juste fine.
public class Weird : Weird.IWeird
{
private interface IWeird
{
}
}
What would be the possible uses of this?
Edit: This question is more specific that this one: "What is a private interface?". It shows that it's possible to implement a private interface from the parent type itself, which seems to be rather pointless. The only use I can think of would be a weird case of interface segregation where you would want to pass an instance of the parent class to a nested class instance as IWeird.
This is probably one of these situations in compiler development when prohibiting something has a higher cost than allowing it. Prohibiting this use would require writing and maintaining code to detect this situation, and report an error; if the feature works as-is, this is an additional work for the team, and it could be avoided. After all, perhaps someone with good imagination could figure out a way to use the feature.
As far as a useful example goes, one potential use is to make another implementation in the class, and use it as an alternative without exposing it to the users of the API:
public class Demo : Demo.Impl {
// Private interface
private interface Impl {
public bool IsValidState {get;}
void DoIt();
}
// Implementation for the error state
private class Error : Impl {
public bool IsValidState { get { return false; } }
public void DoIt() {
Console.WriteLine("Invalid state.");
}
}
private readonly string name;
// Implementation for the non-error state
public bool IsValidState { get { return true; } }
public void DoIt() {
Console.WriteLine("Hello, {0}", name);
}
// Constructor assigns impl depending on the parameter passed to it
private readonly Impl impl;
// Users are expected to use this method and property:
public bool IsValid {
get {
return impl.IsValidState;
}
}
public void SayHello() {
impl.DoIt();
}
// Constructor decides which impl to use
public Demo(string s) {
if (s == null) {
impl = new Error();
} else {
impl = this;
name = s;
}
}
}
As far as best practices go, this design is questionable at best. In particular, I would create a second nested class for the non-error implementation, rather than reusing the main class for that purpose. However, there is nothing terribly wrong with this design (apart from the fact that both IsValidState and DoIt are visible) so it was OK of the C# team to allow this use.

Using different versions of class with static method

I use some library which has class with static method.
namespace lib
{
public class libClass
{
...
public static int num;
public static void libMethod(int arg)
{
num = arg;
}
}
}
I need to use two instances of this class in two different places of my program (in different namespaces). The problem is that this instances should be independent from each other (libClass.num can be different).
I'll be glad if you help me deal with the problem. Thank you for reading.
It's not quite clear why you are in this situation, ie. what you can and can not do.
Ideally, I would just create an instance of the class, and avoid the whole problem, but I assume there is some reason you can't or do not want to do this?
Otherwise the simplest and cleanest way to solve this might be to just make two copies of the class, and put one in each namespace, each with their own static variable.
I would strongly recomend giving the classes different names too, just to be clear and avoid confusion later.
Your final option is to look for a completely different solution. Hard to say without knowing more about your scenario, but if you really can't use an instance, then it seems like num should perhaps not be the responsibility of this class at all.
Obviously, you want to store and use num in some logical context/scope; You should ask yourself which other options (other than that class) you have for doing that within your scope (hope that was not too abstract ^^).
UPDATE:
I see what you mean now. I think you should be able to override the class however. Try something like this:
using VariousTesting;
namespace VariousTesting
{
public class LibClass
{
public static int num;
public static void libMethod(int arg)
{
num = arg;
}
}
}
namespace VariousTesting2
{
public class SubLibClassA : LibClass
{
public static int num;
public static void libMethod(int arg)
{
num = arg;
}
public static int GetNum()
{
return num;
}
}
}
namespace VariousTesting2
{
public class SubLibClassB : LibClass
{
public static int num;
public static void libMethod(int arg)
{
num = arg;
}
public static int GetNum()
{
return num;
}
}
}
You can test it as follows:
SubLibClassA.libMethod(1);
Console.WriteLine(SubLibClassA.GetNum()); // 1
SubLibClassB.libMethod(2);
Console.WriteLine(SubLibClassB.GetNum()); // 2
Console.WriteLine(SubLibClassA.GetNum()); // still 1! Yay! :D

Optimally and elegantly performing certain behaviors based on types in a hierarchy

I am trying to optimize a certain part of my code, which happens to be in a tight performance loop. Mainly I am trying to learn new things which I can apply in the future. My implementation is very lengthy, so I will give a general example of what I am trying to achieve.
My question relates to this: C# 'is' operator performance, and especially to the chosen answer.
Say I have a class A. I also have a class B, which is derived from A. I have a list of type A (which contains a mix of A and B types). In a method where I process these items, I would like to achieve a certain behaviour based on the actual type of the object (not sure if this is the correct way of saying it. Please correct me wherever I say something wrong).
void Process(A item)
{
if (item is A)
{
DoBehavior((A)item); //I know the cast is redundant here, I'm just leaving
//it here for my explanation.
}
else if (item is B)
{
DoBehavior((B)item);
}
}
void DoBehaviour(A item)
{
//perform necessary behaviour for type A
}
void DoBehaviour(B item)
{
//perform necessary behaviour for type B
}
This is the way I currently do it. Note that I iterate over a list of type A, which contains A's and B's. Also, if you feel I did not provide enough code to clarify the situation, I'll gladly expand.
In the question I posted above: C# 'is' operator performance, I have learnt that I can rather change the structure to use an "as" operator, and completely get rid of the explicit cast.
B bItem = item as B;
if (bItem != null)
{
DoBehavior(bItem);
}
This is all good, however, in actuality I do not just have an A and a B, I also have a C, a D, and so on, all deriving from base class A. This will lead to many of these if statements, and they would have to be nested for best performance:
B bItem = item as B;
if (bItem != null)
{
DoBehavior(bItem);
}
else
{
C cItem = item as C;
if (cItem != null)
{
DoBehavior(cItem);
}
else
{
//and so on.
}
}
Now this is ugly. I like writing neat, elegant code, yet I am exceptionally bad at doing it (which often leads me to wasting time trying to just make things look a little better).
I hope this question is not to broad, but firstly I would like to know if there is a more optimal and clean solution at getting the type so that the relevant behavior is performed. If not, is there a cleaner way to use these 'as' operators than nesting it like this?
I suppose one alternative would be to move the behavior into the base class A, and then overriding it for each derived class. However, in a higher thinking sense, the behavior in this particular case of mine is not a behavior of the class A (or it's children), rather, it is some external class acting/behaving on it (which will behave differently for each type). If there is no better way to do it, I will strongly consider implementing it as I have explained now - but I would like some expert opinions on this.
I tried to keep this short, and may have left too much detail out. Let me know if this is the case.
I would strongly suggest that you avoid the "if..else if..else if.." path by programming to interfaces instead of referencing concrete classes.
To achieve this, first make the Process() method ignorant of the type of its parameter. Probably the parameter will end up being an interface like IDoSomething.
Next, implement Process() so that it won't call DoSomething() directly. You'll have to break DoSomething() in smaller chunks of code which will be moved into specific implementations of IDoSomething methods. The Process() method will blindly call these methods -- in other words, applying the IDoSomething contract to some data.
This could be tiresome the more convoluted DoSomething() is, but you'll have a much better separation of concerns, and will "open" Process() to any IDoSomething compatible type, without writing not even one more else.
Isn't that what polymorphism is all about ? A method that has different behavior depending on its type. And I'm fairly sure this would be faster than a "type switch".
And if you need to, you can also use function overloading (for your external processing), see the test program below:
using System;
using System.Collections.Generic;
public class A
{
public String Value
{
get;
set;
}
public A()
{
Value = "A's value";
}
public virtual void Process()
{
// Do algorithm for type A
Console.WriteLine("In A.Process()");
}
}
public class B : A
{
public int Health
{
get;
set;
}
public B()
{
Value = "B's value";
Health = 100;
}
public override void Process()
{
// Do algorithm for type B
Console.WriteLine("In B.Process()");
}
}
public static class Manager
{
// Does internal processing
public static void ProcessInternal(List<A> items)
{
foreach(dynamic item in items)
{
item.Process(); // Call A.Process() or B.Process() depending on type
ProcessExternal(item);
}
}
public static void ProcessExternal(A a)
{
Console.WriteLine(a.Value);
}
public static void ProcessExternal(B b)
{
Console.WriteLine(b.Health);
}
public static void Main(String[] args)
{
List<A> objects = new List<A>();
objects.Add(new A());
objects.Add(new B());
ProcessInternal(objects);
}
}
Note that this will only work with .Net 4.0 !
The best solution for the situation I found is to use a Double-Dispatch/Visitor pattern. I describe a situation where base class A is abstract, and concrete classes B and C inherit from A. Also, by making the DoBehavior method in the base class A abstract, we are forcing ourselves to make an implementation for it wherever we would need it, so if we expand this to add more types, we won't forget to add it's DoBehavior methods (seems unlikely that one would forget, but this behavior may be insignificant to the rest of the new type you add, and may be overlooked - especially if there are many of these behavior patterns)
interface IVisitor
{
void DoBehavior(B item);
void DoBehavior(C item);
}
abstract class A
{
abstract void DoBehavior(IVisitor visitor);
}
class B : A
{
override void DoBehavior(IVisitor visitor)
{
//can do some internal behavior here
visitor.DoBehavior(this); //external processing
}
}
class C : A
{
override void DoBehavior(IVisitor visitor)
{
//can do some internal behavior here
visitor.DoBehavior(this); //external processing
}
}
class Manager: IVisitor //(or executor or whatever. The external processing class)
{
public static void ProcessAll(List<A> items)
{
foreach(A item in items)
{
item.DoBehavior(this);
}
}
void DoBehavior(B item)
{
}
void DoBehavior(C item);
{
}
}
Thanks for contributing, everyone. Learnt a lot and got some good ideas from you all (it's worth it to read all the answers if you face a similar situation).
One simple solution would be to add a field in the base class specifying the class type.
class A
{
// Alternative
string typeName = this.GetType().Name;
public virtual string TypeName { get { return typeName; } }
public virtual string GetTypeName() { return "A"; }
}
class B : A
{
public override string GetTypeName() { return "B"; }
}
class C : A
{
public override string GetTypeName() { return "C"; }
}
class Executer
{
void ExecuteCommand(A val)
{
Console.WriteLine(val.GetType().Name);
switch (val.GetTypeName())
{
case "A": DoSomethingA(val as A); break;
case "B": DoSomethingB(val as B); break;
case "C": DoSomethingC(val as C); break;
}
}
private void DoSomethingC(C c)
{
throw new NotImplementedException();
}
private void DoSomethingB(B b)
{
throw new NotImplementedException();
}
private void DoSomethingA(A a)
{
throw new NotImplementedException();
}
}
You don't really need to use strings, but I prefer that option to using integer for the simple reason that you can't declare 2 class with the same name in the same namespace, therefor if you always return the name class, you have an automatic anti conflict mechanism.

Good practices for designing private methode

Looking at some c# code from open and closed source project i see that private, and sometimes public methods are designed to recive parameters and not directly access the instance variable to extract the parameter they need
class A
{
private B b;
public void Methode1()
{
Methode2(b.SomeProperty);
}
private void Methode2(string param)
{
}
}
Is this considered as a good practice, or it's just a programming way?
Yes, its normal. Consider also moving Methode2 to class B (Tell, don't ask principle):
class A
{
private B b;
public void Methode1()
{
b.Methode2();
}
}
What is bad - passing whole object as parameter for method, when you need only value of it's property (don't pass to method more, than it needs for execution):
class A
{
private B b;
public void Methode1()
{
Methode2(b);
}
private void Methode2(B b)
{
// use b.SomeProperty
}
}
There is no a "good practice" in regard of this subject.
This is a kind of method "overloading" (can not find exact term to define this), maintaining some of them private. That is.
In this concrete example could be that Methode2(string param) is also called from some other part of the class with a different from b.SomeProperty parameter.
So to avoid double code, the developer entroduced a new Methode2(..) method.

C# - using polymorphism in classes I didn't write

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.

Categories

Resources