Using different versions of class with static method - c#

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

Related

Exclusive contracting between two classes or interfaces

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.

Can a delegate be used to call a method of a class without instantiating it?

An interviewer asked me that he has got a heavy class with a number of methods.
He needs to have just one method as of now.
He asked me if Delegates in C# can help me calling that method without instantiating the class?
And he said Yes delegates can help us in this way.
I googled it. I tried running it on my VS but I guess I will need to initialize the class.
Have a look at this snippet -
public class HomeController : Controller
{
public ActionResult test()
{
NumberChanger nc1 = new NumberChanger( /*what to do here!
can i call sum method of class abc*/);
return View();
}
}
public delegate int NumberChanger(int n, int m);
public class abc
{
int a;
int b;
public int sum(int a, int b) {
return a + b;
}
}
If you need to use non-static method, probably you should use new NumberChanger(new abc().sum)
Have a try
You always need at least 1 instance to call an instance method.
But if you want to avoid creating lots of heavy objects, you could use a trick like this:
class TestClass
{
private static TestClass DummyInstance;
public static Action GetShowAsDelegate()
{
DummyInstance = DummyInstance ?? new TestClass();
return (DummyInstance.Show);
}
public void Show()
{
Console.WriteLine("It works!");
}
}
class Program
{
static void Main(string[] args)
{
var show = TestClass.GetShowAsDelegate();
show();
}
}
Your class stores a private static instance of itself, which is instantiated when the caller asks for a delegate version of Show(). It then uses that instance, so you don't need to create one externally each time. After the first call, anyone can run the Show method by getting a delegate, without the need to create any more instances.

Easiest way to re-use a function without instantiation a new class

I currently have a function that looks like this:
public void AnimateLayoutTransform(object ControlToAnimate)
{
//Does some stuff
}
I use this function in a lot of different projects, so I want it to be very reusable. So for now I have it in a .cs file, enclosed in a namespace and a class:
namespace LayoutTransformAnimation
{
public class LayoutAnims
{
public void AnimateLayoutTransform(object ControlToAnimate)
{
//Do stuff
}
}
}
The problem with this is that to use this one function in a given project, I have to do something like
new LayoutTransformAnimation.LayoutAnims().AnimateLayoutTransform(mygrid);
Which just seems like a lot of work to reuse a single function. Is there any way to, at the very least, use the function without creating a new instance of the class? Similar to how we can Double.Parse() without creating a new double?
One option is to make it a normal static method. An alternative - if you're using C# 3.0 or higher - is to make it an extension method:
public static class AnimationExtensions
{
public static void AnimateLayoutTransform(this object controlToAnimate)
{
// Code
}
}
Then you can just write:
mygrid.AnimateLayoutTransform();
Can you specify the type of the control to animate any more precisely than "Object"? That would be nicer... for example, can you only really animate instances of UIElement? Maybe not... but if you can be more specific, it would be a good idea.
You could make it into a static method.
MSDN Example
I find it useful to have a static util class with static methods in them which can be used within the project namespace.
public static class YourUtilsClass
{
public static Void YourMethod()
{
//do your stuff
}
}
You can call it like so: YourUtilsClass.YourMethod()
namespace LayoutTransformAnimation
{
public class LayoutAnims
{
public static void AnimateLayoutTransform(object ControlToAnimate)
{
//Do stuff
}
}
}
LayoutTransformAnimation.LayoutAnims.AnimateLayoutTransform(something);

Is there any way for a static method to access all of the non-static instances of a class?

This is probably a dumb question but I'm going to ask it anyways... I am programing in C#.NET. I have a class that contains a non-static, instance EventHandler. Is it possible to trigger that EventHandler for every instance of the class that exists from a static method?? I know this is a long shot!
You can do this, but you'll need to create a static collection of all your objects:
public class Thing
{
public static List<Thing> _things = new List<Thing>();
public Thing()
{
_things.Add(this);
}
public static void SomeEventHandler(object value, EventHandler e)
{
foreach (Thing thing in _things)
{
// do something.
}
}
}
You'll want to watch out for accumulating too may "Things" . Make sure you remove them from the list when you don't need them anymore.
No, there isn't. Basically there's no way to find all instances of a class, unless you write your own code to do that.
EDIT: Intrigued as to why this is downvoted. Anyway, to add a bit more detail: you should avoid needing to do this. You could make your type implement IDisposable, then register against a static event handler in the constructor, and unregister in the Dispose method. Heck, you could even have a finalizer to do that for you, which will cost you performance but at least not leak if you fail to dispose of the instance.
All of these are somewhat grim options, however. It would be far better to try to redesign so as to avoid the requirement. Perhaps you can give us more information about what you're trying to do, and we can come up with a workaround?
I could be wrong in understanding what you mean, but it should be simple...
This is the main file
using System;
using IdeaClass;
namespace TestIdeas
{
class Program
{
static void Main(string[] args)
{
Ideas i = new Ideas();
Ideas.triggerMany();
Console.ReadLine();
}
}
}
Then there is the Ideas class:
using System;
namespace IdeaClass
{
public class Ideas
{
static OtherClass oc = new OtherClass();
public static void triggerMany()
{
oc.runThing("textual");
}
public Ideas()
{
Ideas.oc.ThingEvent += DoThingHandler;
}
public void DoThingHandler(string thing)
{
System.Console.WriteLine(thing);
}
}
}
And then the other class.
using System;
namespace IdeaClass
{
class OtherClass
{
public delegate void DoThing(string text);
public event DoThing ThingEvent;
public void runThing(string text)
{
if (ThingEvent != null)
{
ThingEvent(text);
}
}
}
}
It does cause unfortunate coupling between the class that raises the event and the class with the static call, but it seems to do what you want.
You can do like this :
public class MyClass{
private static List<MyClass> Instances = new List<MyClass>();
public MyClass(){
lock(typeof(MyClass)){
Instances.Add(this);
}
}}
After this you can do what ever you want with Instances.

Virtual Extension Methods?

I have a class that gets used in a client application and in a server application.
In the server application, I add some functionality to the class trough extension methods. Works great. Now I want a bit more:
My class (B) inherits from another class (A).
I'd like to attach a virtual function to A (let's say Execute() ), and then implement that function in B. But only in the server. The Execute() method would need to do stuff that is only possible to do on the server, using types that only the server knows about.
There are many types that inherit from A just like B does, and I'd like to implement Execute() for each of them.
I was hoping I could add a virtual extension method to A, but that idea doesn't seem to fly. I'm looking for the most elegant way to solve this problem, with or without extension methods.
No, there aren't such things as virtual extension methods. You could use overloading, but that doesn't support polymorphism. It sounds like you might want to look at something like dependency injection (etc) to have different code (dependencies) added in different environments - and use it in regular virtual methods:
class B {
public B(ISomeUtility util) {
// store util
}
public override void Execute() {
if(util != null) util.Foo();
}
}
Then use a DI framework to provide a server-specific ISomeUtility implementation to B at runtime. You can do the same thing with a central static registry (IOC, but no DI):
override void Execute() {
ISomeUtility util = Registry.Get<ISomeUtility>();
if(util != null) util.Foo();
}
(where you'd need to write Registry etc; plus on the server, register the ISomeUtility implementation)
You can use the new dynamic type functionality to avoid having to build a registry of types to methods:
using System;
using System.Collections.Generic;
using System.Linq;
using visitor.Extension;
namespace visitor
{
namespace Extension
{
static class Extension
{
public static void RunVisitor(this IThing thing, IThingOperation thingOperation)
{
thingOperation.Visit((dynamic)thing);
}
public static ITransformedThing GetTransformedThing(this IThing thing, int arg)
{
var x = new GetTransformedThing {Arg = arg};
thing.RunVisitor(x);
return x.Result;
}
}
}
interface IThingOperation
{
void Visit(IThing iThing);
void Visit(AThing aThing);
void Visit(BThing bThing);
void Visit(CThing cThing);
void Visit(DThing dThing);
}
interface ITransformedThing { }
class ATransformedThing : ITransformedThing { public ATransformedThing(AThing aThing, int arg) { } }
class BTransformedThing : ITransformedThing { public BTransformedThing(BThing bThing, int arg) { } }
class CTransformedThing : ITransformedThing { public CTransformedThing(CThing cThing, int arg) { } }
class DTransformedThing : ITransformedThing { public DTransformedThing(DThing dThing, int arg) { } }
class GetTransformedThing : IThingOperation
{
public int Arg { get; set; }
public ITransformedThing Result { get; private set; }
public void Visit(IThing iThing) { Result = null; }
public void Visit(AThing aThing) { Result = new ATransformedThing(aThing, Arg); }
public void Visit(BThing bThing) { Result = new BTransformedThing(bThing, Arg); }
public void Visit(CThing cThing) { Result = new CTransformedThing(cThing, Arg); }
public void Visit(DThing dThing) { Result = new DTransformedThing(dThing, Arg); }
}
interface IThing {}
class Thing : IThing {}
class AThing : Thing {}
class BThing : Thing {}
class CThing : Thing {}
class DThing : Thing {}
class EThing : Thing { }
class Program
{
static void Main(string[] args)
{
var things = new List<IThing> { new AThing(), new BThing(), new CThing(), new DThing(), new EThing() };
var transformedThings = things.Select(thing => thing.GetTransformedThing(4)).Where(transformedThing => transformedThing != null).ToList();
foreach (var transformedThing in transformedThings)
{
Console.WriteLine(transformedThing.GetType().ToString());
}
}
}
}
I would suggest something like the following. This code could be improved by adding support for detecting intermediate class hierarchy types that don't have a dispatch mapping and calling the nearest dispatch method based on the runtime hierarchy. It could also be improved by using reflection to detect overload of ExecuteInteral() and adding them automatically to the dispatch map.
using System;
using System.Collections.Generic;
namespace LanguageTests2
{
public class A { }
public class B : A {}
public class C : B {}
public static class VirtualExtensionMethods
{
private static readonly IDictionary<Type,Action<A>> _dispatchMap
= new Dictionary<Type, Action<A>>();
static VirtualExtensionMethods()
{
_dispatchMap[typeof(A)] = x => ExecuteInternal( (A)x );
_dispatchMap[typeof(B)] = x => ExecuteInternal( (B)x );
_dispatchMap[typeof(C)] = x => ExecuteInternal( (C)x );
}
public static void Execute( this A instance )
{
_dispatchMap[instance.GetType()]( instance );
}
private static void ExecuteInternal( A instance )
{
Console.WriteLine("\nCalled ToString() on: " + instance);
}
private static void ExecuteInternal(B instance)
{
Console.WriteLine( "\nCalled ToString() on: " + instance );
}
private static void ExecuteInternal(C instance)
{
Console.WriteLine("\nCalled ToString() on: " + instance);
}
}
public class VirtualExtensionsTest
{
public static void Main()
{
var instanceA = new A();
var instanceB = new B();
var instanceC = new C();
instanceA.Execute();
instanceB.Execute();
instanceC.Execute();
}
}
}
Virtual implies inheritance in a OOP way and extension methods are "just" static methods that through a bit a syntactic sugar the compiler allows you to pretend to call on an instance of the type of its first parameter. So no, virtual extension methods are out of the question.
Check out the answer by Marc Gravell for a possible solution to your problem.
You can implement a service register. Example (server side):
static IDictionary<Type, IService> serviceRegister;
public void ServerMethod(IBusinessType object)
{
serviceRegister[obect.GetType()].Execute(object);
}
What you need are rather services in your server, which implement server side functionality, instead of extension methods. I wouldn't put to much logic into extension methods.
Let me check: you have a class hierarchy inheriting from A, presumably structured according to your business domain. Then you want to add behaviours depending on where the classes execute. So far you've used extension methods, but now you find you cannot get them to vary with your class hierarchy. What kinds of behaviours are you attaching at the server?
If it's stuff like transaction management and security, policies implemented through dependency injection à la Marc's suggestion should work well. You could also consider implementing the Strategy pattern through delegates and lambdas, for a more limited version of DI. However, what's not clear is how client code currently uses your classes and their extension methods on the server. How dependent are other classes on how you add the server-side functionality? Are they server-side only classes that currently expect to find the extension methods?
In any case, it sounds like you're going to need a careful testability design and testing strategy since you are introducing variation along two simultaneous dimensions (inheritance hierarchy, execution environment). You are using unit testing, I trust? Check that whatever solution you choose (e.g. DI through configuration) interacts well with testing and mocking.

Categories

Resources