I didn't find the answer to my question, but it seems simple. The main big issue is that I bought some library and some functionality hardcoded inside the dll and I can't to recompile that dll without source code. So here is the school level issue:
We have 2 classes A and B
class A {
public void Method1() {
this.Method2 ();
}
private void Method2() {
WriteLine ("A");
}
}
class B : A {
private void Method2() {
WriteLine ("B");
}
}
If we call 'new B().Method1()', then we have the string line "A".
We can't do anything with the class A, but we can change the class B. We should get the string "B".
I've tried to use 'new' modifier, but, as you know, it does not help. The answer "Just override Method1 also" is not the option, cause the real code is much bigger.
Any suggestions?
It sounds to me like you are trying to override Method2 in order to get Method1 to print "B". However, since Method2 is private and non-virtual in class A, this is impossible as defined by C#'s language.
If we can compromise to find a different approach to achieve your desired results, here are some suggestions.
Class composition as a modified boiler plate:
class B
{
private A;
public void Method1() {
this.Method2 ();
}
private void Method2() {
WriteLine("B");
}
public void KeptMethod() {
a.KeptMethod();
}
}
Reflection to call/modify private members:
typeof(A).GetField("privateValue", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(a, "injected string");
typeof(A).GetMethod("privateMethod", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(a, new object[0]);
I know that both of these have there draw backs and limitations, but since I don't know your actual goal, I'm finding it difficult to be more specific.
Related
Someone once wrote:
The space required for an instance depends only on the fields.
The methods require memory too but only one time per class. Like static fields. That memory is allocated when the class is loaded.
But what happens if a class with say like 5 methods and no fields get multiple instances in fields of other classes(composition).
Do they require more memory? Or would it be the same as static methods?
I do ask this question also because maybe it even gets optimised when compiling?
Is there a differents to static class with static methods? Other than u need to create the class each time or pass it around?
Eg.:
class Test1
{
public void DoThis()
{
...
}
public void DoThat()
{
...
}
}
class Test2
{
public void DoSomething()
{
...
}
private Test1 sample = new Test1();
}
class Test3
{
public void DoSomethingElse()
{
...
}
private Test1 sample = new Test1();
}
And so on...
"Behind the scenes", a class method is just like a static method, with the class instance beeing passes by reference as the first parameter.
That is, unless you use virtual methds, which "behind the scenes" are saved as instance members.
That is, because as long as you don't override a method, there is simply no reason to waste an instance's space.
Therefore, the size of both your class instances won't be affected by any non-virtual method you add to the class.
This concept can change between programming languages tho. For example, in Java and Python class methods are virtual by default.
I have trouble understanding lambdas, delegates and so on, I hope with someone giving me a solution to my problem I am able to understand those better. Basically it is possible to create (or change) the body of a method when an object of the class is initialized, no?
Kinda like this:
Let's say I have 1 classes: Class A, which looks like this:
public class ClassA{
int i;
public ClassA(int number)
{
i = number;
}
public void Foo(){}
}
For demonstration purposes very minimalistic, now I also have somewhere else the static main, and what I want to do there is following: Creating multiple objects of ClassA and make it so that when I call ClassA.Foo I get different results I can determine myself, how is it supposed to look Syntax wise?
static void Main(string[] args)
{
ClassA FooBlue = New ClassA(1){
public void Foo()
{
System.Console.WriteLine("I am a Fooranger Blue!");
};
ClassA FooPink = New ClassA(2){
public void Foo()
{
System.Console.WriteLine("My color is the manliest!");
};
...
So now when I do this:
...
FooBlue.Foo();
FooPink.Foo();
System.Console.ReadLine();
}
I get following output on the console:
"I am a Fooranger Blue!"
"My color is the manliest!"
I just mention again that this is an example and by no means anything out of praxis but for the purpose of me understanding that stuff it would be great if someone can provide an answer that gives the desired solution, including the useless integer i.
To accomplish the goal of "providing the implementation of a method when constructing the type" you can indeed use delegates. Simply accept a delegate when constructing the object and invoke it when you want it to be executed:
public class ClassA
{
private Action action;
public ClassA(Action action)
{
this.action = action;
}
public void Foo()
{
action();
}
}
The syntax for a lambda is different than the syntax for creating a named method from a class' definition:
var fooBlue = new ClassA(() => Console.WriteLine("I am a Fooranger Blue!"));
I have following design problem programming application in C#.
I have classes A and B that both derives from C. I cannot change theirs definition because they are defined in external assembly and are not defined as partial too.
What I am trying to achieve is to differ functionality basing on weather provided C object is of type A or B. Of course I dont want to use if statements comparing runtime types of provided object. Is it possible with extensions methods? I dont think so.
Any solution? :)
It should be possible with extension methods by using generics.
Multiple approaches are possible, but this one is simplest. Although you do get that if
public static void Foo<T>(this T objectC)
where T: C
{
if(typeof(T)==typeof(B){ //or for runtime check: if(objectC is B)
//specific
}
}
you could then call Foo on any instance of A or B.
You mention you don´t want if statements, but I'm not sure to which extend you're trying to avoid that? The only way to completely avoid it, is to have 2 extension methods, one for A and one for B, (which in turn can call a common method for C), but I think you're trying to avoid multiple extension methods?
edit If you absolutely want to prevent if's, you'll have to use multiple extension methods as shown in Frederik's post. You could add an extension for the baseclass as well, that only gets called if the type is not known during compilation. But that would still need an if ;)
public static void Foo(this A a)
{
}
public static void Foo(this B b)
{
}
public static void Foo(this C c)
{
if(c is A)
Foo((A)c);
else if(c is B)
Foo((B)c);
else
throw new NotSupportedException(c.GetType().FullName);
}
If the type is always known at compile time, you can simply use the 2 extension methods for A en B.
You could try this:
public static class CExtensions {
public static void DoIt( this B foo ) {}
public static void DoIt( this A foo ) {}
}
But, I don't think that this will work:
C x = new A();
x.DoIt();
I don't think it will compile, but, I can't test it right now.
Purely from a feasibility point of view, it is possible using reflection and extension methods. Whether it makes sense in the context of your application, is something you should judge. Here goes the solution....
class C
{
}
class A : C
{
}
class B : C
{
}
static class Extender
{
public static void M(this B b)
{
Console.WriteLine(" Extension method on B");
}
public static void M(this A a)
{
Console.WriteLine(" Extension method on A");
}
}
static void Main(string[] args)
{
C c = new A();// The actual instance here will be created using some factory.
object instance = Activator.CreateInstance(c.GetType());
Type typeToFind = c.GetType();
Type typeToQuery = typeof(Extender);
var query = from method in typeToQuery.GetMethods(BindingFlags.Static
| BindingFlags.Public | BindingFlags.NonPublic)
where method.IsDefined(typeof(ExtensionAttribute), false)
where method.GetParameters()[0].ParameterType == typeToFind
select method;
// You would be invoking the method based on its name. This is just a quick demo.
foreach (MethodInfo m in query)
{
m.Invoke(instance, new object[] { instance });
}
}
To me this feels like a flaw in design.
If you can't have a common class to two sub classes which override and changes functionality without knowing the run time type you clearly have some issues with the overall design.
Should that functionality that differ depending on run time types really reside in those classes at all?
You could do it this way. Create a class with the different methods you need. In the same class define a delegate with the signature of this methods and keep a Dictionary where the keys are the types, and the values the delegates. Finally you can create an extension method for your class C that look into the dictionary using the type of the object that's executing the method itself and executes the right method. Something like this:
public static class CExtender
{
private static void DoItA(C anA)
{
MessageBox.Show("A");
}
private static void DoItB(C aB)
{
MessageBox.Show("B");
}
private static void DoItC(C aC)
{
MessageBox.Show("C");
}
delegate void DoItDel(C aC);
private static Dictionary<Type, DoItDel> _doItDels;
private static Dictionary<Type, DoItDel> DoItDels
{
get
{
if (_doItDels == null)
{
_doItDels = new Dictionary<Type, DoItDel>();
_doItDels[typeof(A)] = new DoItDel(DoItA);
_doItDels[typeof(B)] = new DoItDel(DoItB);
}
return _doItDels;
}
}
// the only public part is the extension method
public static void DoIt(this C aC)
{
DoItDel aDel;
if (DoItDels.TryGetValue(aC.GetType(), out aDel))
aDel(aC);
else
DoItC(aC);
}
}
You can use Decorater pattern in this case.
i.e. you can have 2 new classes of your own let say A1, B1 both deriving from C. (provided C is not a sealed class. If that's the case solution would be a bit different). Also A1 and B1 needs to wrap A and B corespondingly. You could inject instances of A and B through the constructors of A1 and B1.
You can also have a common interface which A1 and B1 both implmement. Interface needs to have the method which you need A1 and B1 to implement in their own ways. (A1 and B1 can delegate the calls to A or B as needed)
This way, in your client code, you can refer to A1 and B1 instances by their interface type and perform the common operation defined in the interface without knowing what their actual concrete implementations are.
Let me know if you need a code sample if I wasn't clear.
OK I found the answer.
The dynamic keyword is the clue here.
We can write:
void Handle(C c)
{
dynamic cc = c;
HandleSpecific(cc);
}
void HandleSpecific(A a)
{
//Specific behavior A
}
void HandleSpecific(B b)
{
//Specific behavior B
}
Drawbacks are of course - Risk of exception beacause of runtime binding introduced here and slight performance hit.
I have the following situation:
In a 3rd party library (can not be modified):
class A { public virtual void M() {} }
class B : A { public override void M() {} }
In my own code:
class C : B { public override void M() {} }
From C's implementation of method M I want to call A's (but not B's!!). Can I?
Any tricks accepted, reflection included. I tried reflection already, but using the MethodInfo that I get from typeof(A) still generates a virtual call (calling C's implementation with subsequent stack overflow).
Deriving C from A is out of the question due to the complexity of reimplementing B.
you can generate dynamic method to make proxy that use Call (not CallVirt) instruction
var x = new C();
var m = typeof (A).GetMethod("M");
var dm = new DynamicMethod("proxy", typeof (void), new [] {typeof(C)}, typeof (C));
var il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, m);
il.Emit(OpCodes.Ret);
var action = (Action<C>)dm.CreateDelegate(typeof (Action<C>));
action(x);
Quite old question but I had a similar problem recently.
desco's answer gave the crucial hint.
But the generated proxy delegate should be encapsulated in class C, can be static and initialized via static constructor so time consuming reflection will be required only once.
// -- in foreign assembly
class A { public virtual void M() { Console.WriteLine("A.M"); }}
class B : A {public override void M() { Console.WriteLine("B.M"); }}
//
// -- in own assembly
class C : B
{
private static Action<C> call_A_M;
public override void M() {
call_A_M(this);
Console.WriteLine("C.M");
}
static C()
{
var m = typeof(A).GetMethod("M");
var dm = new DynamicMethod("", typeof(void), new[] { typeof(C) }, typeof(C));
var il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, m);
il.Emit(OpCodes.Ret);
call_A_M = (Action<C>)dm.CreateDelegate(typeof(Action<C>));
}
}
But as Dan Bryant already mentioned: never ever use such dirty tricks in production code.
In my previous answer I missed the fact that A and B are in an external library and cannot be modified. In that case, I would suggest a different approach. Basically, if the design flaw is in B, you can’t use B. Subclass from A instead.
The unfortunate consequence of this, of course, is that you may need to reimplement some or all of the functionality in B. You may be able to copy the code from Reflector if necessary. I realise that this sounds undesirable, but I still think it is preferable to using unmodifiable code that has a known issue that causes you problems.
I’m afraid this is not possible directly the way you describe — the purpose of virtual methods is for the overriding to be transparent. So the only way to do this at all is via a workaround.
Let me try to whip one up, but please be aware that this is a hacky suggestion. If you really need this construct in your code, it may be an indication that your code has a fundamental design flaw somewhere else, so restructuring something might be more desirable than filling it with yet another design flaw. But anyway, here goes...
class A {
public virtual void M() { m_protected(); }
protected void m_protected() { /* code goes here */ }
}
class B {
public override void M() { /* code here, possibly invoking base.M() */ }
}
class C {
public override void M() { m_protected(); }
}
You cannot do that. You should probably design your class hierarchy differently, because it looks strange that C inherits from B, while behaving like A.
Anyway, it could make sense in your case. Then you should make another method in A which you will not override:
class A {
protected virtual void basicM() {}
public virtual void M() { basicM(); }
}
class C {
public override void M() { basicM(); }
}
BTW, if you name the method as I did in the example, then you should probably rethink the whole thing. If this hierarchy is justified, than basicM probably performs something that deserves to be a separate method with a different name, perhaps even a public method.
In C# is it possible to create a function that can only be called from within another function?
e.g., can you do something like this?
private void a()
{
b();
c();
...do something else
private void b()
{
..do something but can only be called from a()
}
private void c()
{
..do something but can only be called from a()
}
}
The reason I want to do this is that function b() and c() split some implentation details of a() and they are just cleaner and easier to read in their own scope. However, these functions are of no use to the class as a() does some handling after they are called which must take place.
Use an anonymous nested function maybe?
I wouldn't worry about taking explicit steps to ensure b() and c() are only called by a().
It makes sense to worry about the public methods you expose on a class, since you're providing an interface to the outside world, potentially to people who don't have access to the source code of your class (or at the very least don't want to worry about the implementation details of your class).
Inside your class, though, you should feel free to have whatever private methods you want for whatever reasons you want. Code re-use is one reason to create a new private method, but creating multiple smaller, single-use methods to break up a larger one is also a perfectly valid (and common) reason.
Beyond that, for future maintainers of your code a simple comment like:
//this method should only be called by a()
private void b()
{
...
}
is going to be far more understandable than most of the other solutions presented here.
Using a delegate you can do:
public voidMyFunction()
{
Func<string> myFunction=(s)=>Console.WriteLine(s);
foreach(string str in myStringList)
{
myFunction(str);
}
}
The short answer is no; however, you can create an anonymous delegate or lambda expression as your internal b() method.
You could use the StackFrame class to check at runtime who's the caller of the function:
public class MyClass
{
public static void A()
{
B();
}
public static void B()
{
var stackTrace = new StackTrace();
if (stackTrace.FrameCount < 1 || stackTrace.GetFrame(1).GetMethod() != typeof(MyClass).GetMethod("A"))
throw new InvalidOperationException("Not called from A()");
}
}
But that is
1) Only at runtime
2) Slow
3) A really dirty hack
Well you could use reflection and just get the calling method name and throw an exception if it were anything other than A.
http://www.csharp-examples.net/reflection-calling-method-name/
But if b and c are private they can only be called from within that class anyway, and if you're the only one that is writing the class, then i fail to see the problem. So it seems to me its not a coding problem but rather one of policy.
I'd just document the intent in the method headers/comments.
Similar Question Here - Note the comments on the answer
Not exactly but you could implement both within their own class. Mark b() as private.
To gain the effect of only a() calling b(), either do as Andrew noted already, by putting a() and b() in a class and marking b() appropriately. If you're working inside of an assembly that you control totally, you could use internal instead of private if a() and b() will be in different classes, but in the same assembly. Then user code cannot call it (from outside of your assembly, that is, from their application program) and you can control via policy the writing of your assembly.
You can also create something like this:
internal abstract class SecretFunctionWrapper
{
private void MySecretFunction()
{
...
}
protected void FunctionWhichCalls()
{
...
MySecretFunction();
}
}
public MyRealClass : SecretFunctionWrapper
{
...
}
This will work only for one function. You can also try nested private class like this:
public class A
{
private static class Wrapped
{
private static void A()
{
secred code
}
public static void B()
{
A();
}
}
public void UsingA()
{
Wrapped.B();
}
}
i dont know but maybe Code by Contracts may help but this is not supported natively
Maybe easier to use #region in this case
You could use the internal keyword and put both those functions inside the same class, while leaving other other functions in a different class:
http://msdn.microsoft.com/en-us/library/7c5ka91b.aspx