I have around 300 functions and don't want to have to make a wrapper for each of them.
class B
{
func(vartype somevar, int otherparam)
{
//code
}
}
Then I want to do this
class A:B(vartype somevar)
{
Asfunc2()
{
this->func(1); //basically somevar would already be filled in when called and it'd just need the 1 param.
}
}
You could call base constructor as follows:
public class Manager : Employee
{
public Manager(int annualSalary)
: base(annualSalary)
{
//Add further instructions here.
}
}
The reference is here.
What you described is looks like binding function parameters in JavaScript but it's not possible in C# as far as I know.
I was thinking about the situation you described and was using the following linqpad script to go over what this would imply:
void Main()
{
B b = new B();
b.CallA().Dump();
}
class A
{
public string CallA(string someVar)
{
return string.Format("{0} says Hello", someVar);
}
}
class B : A
{
public string CallA(string someVar = null)
{
return base.CallA(someVar);
}
}
You essentially end up with an overloaded CallA method. This can will get sticky. What about the following code that you would execute in the Main method after creating an instance of B:
((A)b).CallA(); //You actually want to call A.CallA
This still calls b.CallA().
Just be careful. This does not feel like a good design.
If you have access to class B, then I believe the only way to do what you want is to make somevar a global variable, which will be initialized in the constructor.
You might be able to get around this with reflection, but it seems more likely you have a code smell, and the real problem is in the design, not the implementation.
Related
I'm learning ADO.NET and here is an example of method call from MS Documnetation:
workAdapter.TableMappings.Add("AuthorsMapping", "Authors");
Where workAdapter in an instance of DataAdapter class, TableMappings its property, and Add its method. I have never seen method being invoked in this way. I wasn't able to find an answer here nor in the documentation. Need help understanding this.
Properties and methods are invoked this way a lot. You can chain as many together as you like and it makes sense to do so if you only need to use each one once. Any time you could assign something to a variable and then access a member via that variable, you can access it for what you originally assigned. If you have these types:
public class Thing
{
public Stuff Stuff { get; set; }
}
public class Stuff
{
public void DoSomething()
{
// ...
}
}
then you could do this:
var s = new Stuff();
var t = new Thing { Stuff = s };
s.DoSomething();
t.Stuff.DoSomething();
In those last two lines, s refers to the same object as t.Stuff so you can call the same DoSomething method on both.
In C++ I can declare a fully functional anonymous class inside a piece of code where it's needed so that I don't have to declare it if I need it only once.
The code should be like this
Class MyClass
{
Class
{
String string1;
String string2;
void MyMethod();
} Strings;
}
And call it the members with MyClass.Strings.string1, MyClass.Strings.MyMethod() and so on. This way I can elegantly group my code.
Is there a way to do the same thing in C#?
This way I can elegantly group my code.
I don't how can this help you to elegantly group your code, but there is no such thing in C#. There are anonymous classes but they only work in local scopes:
// inside a method:
var obj = new { String1 = "Hello", String2 = "World" };
And you can't add methods to them.
The closest thing you can get to is an inner class/struct:
class MyClass
{
class MyStrings
{
String string1;
String string2;
void MyMethod() { ... }
}
MyStrings Strings;
}
I agree Sweeper. This functionality adds just cluttering code. You should consider to make your code as easy as possible to understand. This means if you feal that you want to group your code, giving every group it´s own functionality, why not make this group a class and give it a name that directly reflects what its purpose is.
What you can do is use an anonymous class which in C# doesn´t implement any interface but just derives from object:
var a = new { MyMember = 1, MyFunc = new Func<int>(() => 1) };
now you can invoke both members of this type:
Console.WriteLine(a.MyMember);
var retVal = a.myFunc();
But does this make your code any better in a way that it´s easier to understand what it does? I doubt so. Give your instances - even when used only once - a name that describes what their intention - the idea behind - is. Don´t make it hard for others to understand your code by cryptifying it.
Apart from this you can restrict the use of your class to be private by nesting it within another one:
public class MyClass
{
private class Strings { /* ... */ }
}
Now your class is just visible to itself and within MyClass (and in other classes that are nested in MyClass of course). This makes it impossible to access the class from the outside like so:
var strings = new MyClass.Strings();
Try making the inner class static. That way you will be able to use the syntax you describe:
class MyClass {
public static Strings {
public static string string1;
public static string string2;
public static void MyMethod() {}
}
}
You can then call: MyClass.Strings.string1 = "Hell, world!";
In my project, I have many DLL assemblies referenced. One of those DLL's contains the bool method that I want to change. I do not have the original source for the DLL and using a Reflector to decompile a project seems impractical. All I want to do is intercept or override this method or method call so that I can change it's return value to match my own method outside of said DLL.
Any such way to do this? Thanks!
Edit:
Here is an example:
public virtual bool isOwner()
{
return false;
}
Essentially, I just want to change getOwner to return true;
If the class is public and the method is marked as virtual, then you can simply override it with this syntax:
public MyClass : TheClass
{
public override ReturnType MethodName(Arguments)
{
//class the base class implementation if needed
//base.MethodName(Arguments)
//do your own stuff and return whatever is needed
}
}
Hope this helps
EDIT: A word of caution though, this won't replace the calling code within the DLL. It will only work if you instantiate the derived class yourself and call it from your code.
Is there a general way to do what you want, built into .NET?
Yes, and no.
If you want every usage of class X' method Y to be replaced by some other code, then no, there is nothing built into .NET class system or compiler that will do this.
If you can inherit from class X, overriding method Y, and then ensure that all places where class X is used, your new class is used instead, then yes, that is the proper way to do this.
This is easily done:
public class YourFixedClass : TheProblematicClass
{
public override string YourProblematicMethod()
{
// probably call the problematic method through base.
// and fix the return value, or fix the parameters
// or don't call it at all, re-doing whatever it does
}
}
Or, if you can make a new class that implements all the same interfaces, wrapping (delegating) all the methods and properties of the original (problematic) class, then that might be doable, but this requires all actual usage of the class to go through the interfaces.
As this:
public class Wrapper : IInterface1, IInterface2
{
private readonly YourProblematicClass _C;
public Wrapper(YourProblematicClass c)
{
_C = c;
}
public string YourProblematicMetho()
{
// probably call the problematic method through _C.
// and fix the return value, or fix the parameters
// or don't call it at all, re-doing whatever it does
}
}
If, on the other hand, you don't have control of where all the code is that calls the class/method, then no, you can't do any of this.
So what else is there? Well, there is always the debugger interfaces. You can make a program that is somehow the debugger of itself, patching in the right code upon demand, but this is likely to be extraordinary difficult to get right.
In short, no, there is no way to do what you want. You need to find a different way to accomplish this.
Have you thought about changing the original assembly in the first place? I understand that you don't have the source code for it, but is that because:
You lost it
You didn't make it
In point 1, I would really work towards recreating the source code, either through a decompiler or similar, and get a new project going to fix that.
In point 2, have you thought about contacting the people that made it and asking them for help?
Uhm Ok you can do something like this:
public class MyNameClass : MyDllname.MyClassName
{
public bool isOwner()
{
return !base.isOwner();
}
}
Then you have override the method and you can use all the other methods in the DLL simply using an istance(if there aren't static) of the MyNameClass
You can use "new" modifier.
See example on http://msdn.microsoft.com/en-us/library/435f1dw2.aspx
Or this:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(new ClassA().IsEvenDayToday()); // Result: true
Console.WriteLine(new ClassB().IsEvenDayToday()); // Result: false
Console.ReadKey();
}
}
public class ClassA : ClassB
{
public new bool IsEvenDayToday()
{
return DateTime.Now.Day % 2 == 0;
}
}
public class ClassB
{
public bool IsEvenDayToday()
{
return DateTime.Now.Day % 2 != 0;
}
}
We're working with XML and want a common interface amongst the main XML class and all of its components. However, sub-components of the XML class need additional methods, but they also need the main component's methods. Seems like a great use for inheritance.
Here is some code I wrote to accomplish this task. Hopefully, you can get a good idea of what we're going for based on usage:
using System;
namespace SampleNamespace
{
public class SampleClass
{
public static void Main()
{
var xmlDocumentFiles = new XmlDocumentFiles();
xmlDocumentFiles.Files.RootFile.SetFileName("Example.xml");
System.Console.WriteLine(
xmlDocumentFiles.Files.RootFile.GetFileName()
);
}
}
public class XmlDocumentFilesRoot
{
protected string _rootFileName;
public FilesClass Files { get { return (FilesClass) this; } }
}
public class FilesClass : XmlDocumentFilesRoot
{
public RootFileClass RootFile { get { return (RootFileClass) this; } }
}
public class RootFileClass : FilesClass
{
public void SetFileName( string newTitle )
{
_rootFileName = newTitle;
}
public string GetFileName()
{
return _rootFileName;
}
}
public class XmlDocumentFiles : RootFileClass
{
}
}
I was able to cast to child classes and to my surprise it runs just fine. Assuming nothing is put inside of the sub-classes other than methods which wouldn't make sense in the parent, will there ever be any problems (weird compilation errors, runtime crashes) with this class structure?
Are there any alternatives? I had initially tried nested classes + extension methods located outside of the main class, but there was a lot of code needed to set that up. See: https://stackoverflow.com/questions/19415717/using-c-sharp-extension-methods-on-not-in-nested-classes-to-establish-a-common
Extending functionality of a class, sounds like a decorator pattern.
Here's a head-first pdf on this subject:
http://oreilly.com/catalog/hfdesignpat/chapter/ch03.pdf
Also; I would like to discourage the triple '.' :
xmlDocumentFiles.Files.RootFile.SetFileName("Example.xml");
2 is evil, if you need 3: you will definitely lose maintainability.
Hope it helps.
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