Is there any way I can emulate C++ value template parameters in C#?
template<bool flag>
void Method()
{
// Do some work
if constexpr(flag)
{
// Do something specific
}
// Do some more work
}
So that it would generate two versions of a method which can be called like this:
Method<false>();
Method<true>();
This is for performance reasons, so it is better to not make additional calls inside the Method. The Method is performance critical part and it is called billions of times so it is important to squeeze every CPU cycle from it.
On the other hand it has a rather complicated logic, so I would prefer to not have two copies of it.
I think I could do something with generics, but it wouldn't be the best option for performance. So now the only way I can think of is to create some kind of template code generator for it. But maybe there are other options?
Maybe it is possible to compile two versions of the method using Roslyn, so that it would create two optimized versions of it with specific arguments?
void Method(bool flag)
{
// Do some work
if (flag)
{
// Do something specific
}
// Do some more work
}
So that I can compile it to:
void Method_false(false)
{
// Do some work
// Do some more work
}
and to:
void Method_true(true)
{
// Do some work
// Do something specific
// Do some more work
}
Is it at all possible?
Metaprogramming is not possible in C#. Look for possible alternatives in the form of code transformation tools in the following SO question: Is metaprogramming possible in C#?
You can't do this from language directly, however it is possible because JIT is smart enough. Create an interface and two structs:
public interface IBool
{
bool IsTrue();
}
public struct True : IBool
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsTrue()
{
return true;
}
}
public struct False : IBool
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsTrue()
{
return false;
}
}
Please note that implementations of IsTrue are marked with MethodImpl attribute. Now rewrite your Method as generic:
public static void Method<T>(ref T flag) where T : struct, IBool
{
if (flag.IsTrue())
{
Console.WriteLine(42);
}
else
{
Console.WriteLine(24);
}
}
There is important thing: T has struct constraint so JIT aware that there is no inherited types from T and nobody can override return value of IsTrue. Also, because this method will be inlined, JIT replace call to IsTrue with constant. And when you have
if (false)
{
// some code
}
that means that whole code block will be removed. As a result JIT will create two implementations of Method: first with content of if section and seconf with content of else section. You can check this in disassembly window:
Related
I'm trying to create a mechanism that will allow the application to decide (in runtime) whether to execute some functionality.
"Some Functionality" can be anything, it can be c# code which is contained in several classes in several dlls, it can be UI, it can be database query execution, etc.
Most importantly, it should fit in the current existing infrastructure I have, which I cannot re-design and build from scratch.
The more I think of it, it seems like the only solution I can use would be to hold some table which will be the "functionality repository" and it will tell (by unique key) if a functionality is on / off.
Then in code, I will have to place in each spot which handles such functionality an if else statement.
E.g.
If(functionalityEnabled)?
DoFunctionality()
Else
DoTheUsusal()
Is there a better way or a better design to implement it? I would like to keep the solution as simple as possible, but on the other hand, this solution is really ugly and will eventually make my code looks like spaghetti code.
Your thoughts will be appreciated,
I'm using c# with sql server, web api for web services.
Edit:
I want to say that I appreciate the time and effort of everyone answering my question, there were some really interesting ideas that you brought up.
I eventually marked #dasblinkenlight answer since it suited by need the best, though other answers here are really good and may be useful to others.
Thank you.
If you have two classes that implement the same interface, your application can call the functionality (methods, properties) of the class without knowing exactly if it is calling the basic functionality or the alternative functionality:
IFunctionalityX {
DoIt();
}
class BasicFunctionalityX: IFunctionalityX {
public DoIt() {
// Default behaviour goes here
}
}
class PluginFunctionalityX: IFunctionalityX {
public DoIt() {
// Alternative functionality.
}
}
If PluginFunctionalityX shares parts of its implementation with BasicFunctionalityX, you may inherit it from the other, but whether you do or not doesn't really matter. As long as you use the interface, that is what counts, and you can use this method regardless of whether the classes are related or not.
In the initialization of your program, you can make the decision once and create an instance of the right class. You may store this class in some container that holds all your functionalities. FunctionalityX is a property of interface IFunctionalityX, and you can make other interfaces (and properties) for other functionalities.
if (functionalityXEnabled) {
FunctionalityContainer.FunctionalityX = new PluginFunctionality();
} else {
FunctionalityContainer.FunctionalityX = new BasicFunctionality();
}
Then, in the rest of your application, you can call your functionality through:
FunctionalityContainer.FunctionalityX.DoIt();
Instead of implementing this from scratch you may use a dependancy injection library, like Unity. This also allows you to more easily get an instance of the right functionality at the time you need it without having to create them all at the start of your program, and without writing elaborate constructor code for all fucntionalities.
You want to dispatch your code differently at runtime dependent on a configuration setting. Conditionals and polymorphism are two ways of doing so.
Conditionals
At runtime, check for values using if, switch or other lookup methods. You're already doing these.
if (configFile.cloudAccount == null) {
saveFileToDisk();
} else saveFileToCloud();
Advantages
They're conditionals, you really can't avoid having to do one at some point in any nontrivial development project
Disadvantages
Doing them at every point in your application would be painful, though. So they're best combined with other strategies to minimise their use
Polymorphism
When loading your application, read through the configuration file and construct your application's components accordingly:
interface IFileSaver { /* Used to save files in your application */ }
class DiskSaver : IFileSaver { /* The default file saving class */ }
class CloudSaver : IFileSaver { /* If they've configured a cloud account */ }
// EXAMPLE USE
int Main (...) {
// Setup your application, load a config file.
// You'll need to check the config with a conditional
// here (uh oh) but other components of your application
// will just use the IFileSaver interface
if (configFile.cloudAccount != null) {
YourApplication.FileSaver = new CloudSaver(configFile.cloudAccount);
} else {
YourApplication.FileSaver = new DiskSaver();
}
}
// Somewhere else in your application
void SaveCurrentDocument() {
// No if's needed, it was front loaded when initialising
// the application
YourApplication.FileSaver.Save();
}
Advantages
Fits in nicely with object-oriented design
All your configuration checks are front loaded. After loading in the correct classes the rest of your program will use them, oblivious to their actual implementation. Because of that, you don't need to do if checks throughout your code.
Compiler will be able to statically check type errors in your approach
Disadvantages
Only as flexible as your class's interface. Maybe you want some extra steps and checks to occur with a CloudSaver, they'd better fit into the pre-existing interface; otherwise, they won't happen.
Long story short - conditionals let you explicitly perform the checks whenever they're needed so, in principle, you get a lot of procedural flexibility. For example, maybe the SaveAs routine needs to save files slightly differently than the Save routine. However, as you've identified, this leads to long repetitive code. In those cases, structuring your code to use polymorphism might help out.
Either way, you will almost certainly need to have some amount of conditional checks wherever there is flexibility in your application.
Note: There are many other ways of achieving runtime config checks, I'm just pointing out the most common (and usually straightforward)
A once-popular quip among OO programmers has been that every conditional in the code indicate a missed opportunity to subclass. Although this rule is far from being universal, and it falls short when it comes to composition, there is a grain of truth to it, especially when you see the same condition popping up in multiple ifs across different methods of the same class.
A common way of dealing with ifs like that is using some combination of inheritance and composition, and moving the decision to a single place where your object is being created.
The inheritance way looks like this:
interface Doer {
void doSomething();
}
class BasicDoer implements Doer {
public void doSomething() {
...
}
}
class EnhancedDoer extends BasicDoer {
public void doSomething() {
base.doSomething();
...
}
}
// At construction time:
Doer doer;
if (someCondition)
doer = new BasicDoer();
else
doer = new EnhancedDoer();
The composition way looks like this:
interface Doer {
void doSomething();
}
// Create several implementations of Activity, then...
// At construction time:
List<Doer> doers = new ArrayList<>();
if (someCondition1)
doers.add(new SomeKindOfDoer());
if (someCondition2)
doers.add(new AnotherKindOfDoer());
if (someCondition3)
doers.add(new YetAnotherKindOfDoer());
Now instead of an if you do this:
for (Doer d : doers) {
d.doSomething();
}
If it's just a single condition then you have no choice but to use if else and is perfect for single conditions.
If you have more then 1 condition, you may think of using Switch statement.
As far as you are worried about your code going to look complicated with if else statement, put your code within functions,
if(condition)
{
DoThis();
}
else
{
DoSomethingElse();
}
Maybe something similar to strategy design pattern (incapsulation of behaviour) will make it more managable if functionality doesn't require lots of interaction with object data (though interaction is possible). Pros: readable extendable code, cons: lots of code.
namespace SomethingLikeStrategy
{
public interface Behaviour {
void doThis();
void changeM(ref int m);
void doThat();
}
public class BehaviourOriginal : Behaviour {
public void doThis() {
Console.WriteLine("foo");
}
public void changeM(ref int m) {
m = 20;
}
public void doThat() {
throw new Exception("not implemented");
}
}
public class BehaviourSpecial : Behaviour {
public void doThis() {
Console.WriteLine("bar");
}
public void changeM(ref int m) {
m = 10;
}
public void doThat() {
throw new Exception("not implemented");
}
}
public class MyClass {
Behaviour mBehaviour;
int mM = 0;
public MyClass() {
mBehaviour = new BehaviourOriginal();
}
public void setSpecialBehaviour(bool special) {
if (special) {
mBehaviour = new BehaviourSpecial();
} else {
mBehaviour = new BehaviourOriginal();
}
}
public void doThis() {
mBehaviour.doThis();
}
public void doThat() {
mBehaviour.doThat();
}
public void changeM() {
mBehaviour.changeM(ref mM);
}
public void printM() {
Console.WriteLine(mM);
}
}
class Program
{
public static void Main(string[] args)
{
MyClass myClass = new MyClass();
myClass.doThis();
myClass.setSpecialBehaviour(true);
myClass.doThis();
myClass.setSpecialBehaviour(false);
myClass.printM();
myClass.changeM();
myClass.printM();
myClass.setSpecialBehaviour(true);
myClass.changeM();
myClass.printM();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
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;
}
}
I've found a nice link on C++ Tenmplates:
http://www.cplusplus.com/doc/tutorial/templates/
and needed something similar in C#. I have a solution that seems to work but wanted opinions of others in how it relates to the above link, specifically the specialization section.
Here is a proof of concept I came up with:
public abstract class Piece
{
public object Value { get; set; }
}
public class Rook : Piece
{
public void Capture()
{
int i = (int)this.Value;
}
}
public class Pawn : Piece
{
public void CaptureEnPassant()
{
string s = (string)this.Value;
}
}
public class PieceFactory<P, T> where P : Piece, new()
{
P p;
public PieceFactory(T value)
{
p = new P();
p.Value = value;
}
public P GetPiece()
{
return p;
}
}
and then finally to call into the factory I do this:
var piece = new PieceFactory<Pawn, string>("exd6").GetPiece();
piece.CaptureEnPassant();
I've seen different solutions like using extension methods and other ways...
Just wanted to see if my way of thinking is along the lines of good patterns.
THanks so much,
David
My opinion is that your sketch is far more complex and confusing than necessary. Why does the base class have a "value" that has different meanings and different types in each derived class? Why is there a factory that takes a type parameter that must be of a particular type argument, and if it is not, then the program crashes at runtime? Get rid of all that brittle, confusing, fragile stuff. If a pawn needs a string, then make a public constructor on Pawn that takes a string, end of story. There's no need for the factory pattern at all here.
Don't be so in love with the tool that you build stuff out of it that doesn't actually make any sense. Generic types are great for things like collection classes. They're not a good fit for the chess domain.
FYI I tried converting my own template-programmed chess engine into C# for fun, and found it was slower by roughly a factor of 20 across the board [sic].
That includes stuff like parsing the gamefile format. Position lookup and move generation just had a lot of mechanical sympathy in the C++ version, that applying all the tricks could not make up for:
compiletime optimization
non-shared generics (mono specific - see here, e.g.)
unsafe code (pinned arrays, raw pointers),
unchecked blocks (as in array bounds/arithmetic overflow
value typed arrays and ref passing
short, inlinable functions
garbage prevention (custom allocation in preallocated 'realms' (just large arrays of structs preallocated)
That said, the performance benefit from using generic collections is significant, esepcially for, say List<T> where T : struct. Note however, the caveats from the link above (especially for the new constraint which has rather pathetic performance on MS. NET due to code sharing; it is basically as slow as using reflection to call the constructor, even for value types).
YMMV, but in the end I'd say
1. Go with the C# way. If you must optimize, do it the C# way
2. If all else fails, resort to P/Invoke (C++/CLR is a sweet spot if you target Windows)
I would just use generics on your base class. Does this break something in your code?
void Main()
{
var factory = new PieceFactory<Rook, int>(20);
factory.GetPiece().Dump();
}
abstract class Piece<TValue>
{
public TValue Value { get; set; }
}
class Rook : Piece<int>
{
public int Capture()
{
// Do something...
return base.Value;
}
}
class Pawn : Piece<string>
{
public string EnPassant()
{
// Do something...
return base.Value;
}
}
class PieceFactory<TKey, TValue> where TKey : Piece<TValue>, new()
{
private readonly TKey piece;
public PieceFactory(TValue value)
{
this.piece = new TKey();
this.piece.Value = value;
}
public TKey GetPiece()
{
return this.piece;
}
}
I have also put some access keywords (like this and base) and a readonly modifier in your factory.
I would look this up on Google/MSDN, but I have no idea what it's called so I'm asking here.
In Java, I seem to remember you can do this really cool thing like:
Class MyClass
{
int number;
MyClass() { }
void setNumber(int number)
{
this.number = number;
}
}
and then do something like:
MyClass myClass = new MyClass()
{
override void setNumber(int Number)
{
this.number = 2 * number;
}
};
...or something. Forgive any mistakes I made above - I haven't actually touched Java in about 6 years.
The point is, I remember you could pseudo-extend a class inline.
Right now, I need to extend a C# WinForms control, but I only need to use it once, and the modifications are very minor. All I need to do is to override the CreateParams property and OnPaint() handler.
My solution is already getting huge with classes all over the place, it seems like a shame to include yet another class which is basically identical to a standard .Net control, just with very slightly different behaviour.
Is it possible to do this inline-extension in C# like you could in Java? If so, how? (and what is it called so I can look it up on MSDN?)
This (explicit nominative anonymous types) is not possible in C#3/4.
The types must be created explicitly and then constructed. Tasks are sometimes "inverted" in C# with the use of Events and Delegates (class invokes Event which supplies implementation such as "NeedDataSource") -- arguably because of this, although it just makes sense in many cases.
If is possible to create explicit non-nominative types: var x = new { P = 1, }; but only in a local scope. Implicit methods include delegates/lambdas/anonymous functions and do not apply here.
Happy coding.
I understand that you said this cannot be done in C#, but its possible to rewrite this to C# but with not too much complicated method?
new EffectClause("Sleep Clause", SleepEffect.class)
{
public String getClauseDescription()
{
return "Bla bla bla";
}
public boolean isEnabledByDefault()
{
return true;
}
};
The feature you're looking for in C# is called Extension Methods. They are similar, but instead you make code such as:
public static void setNumber(int Number, MyClass target)
{
target.number = 2 * number;
}
You usually include this in your own extensions namespace, then bring it into scope when necessary by using MyExtensions; C# is able to figure out that you mean to call this method when you call whatever.setNumber(x);
I'm not 100% sure if this will let you override a method that already exists in a class however. Your other option is to inherit from the target class with a class specifically for the purpose of overriding the target method.
I have the following code:
class Foo
{
public Foo()
{
Size = true;
}
private bool _size;
protected bool Size
{
get { _size; }
set { _size = value; }
}
}
class CrazyFoo : Foo
{
public void First()
{
if (!Size)
return;
}
public void Second()
{
if (!Size)
return;
}
public void Finished()
{
if (!Size)
return;
}
}
What is the best way to implement this sort of pattern, as it drives me nuts to type
if(!Size) return;
perhaps I can do it with attributes or AOP?
What is the best and simplest way?
Thanks
If you have the same guard statement at the beginning of too many methods, you can create a method called executeWithGuard:
private void executeWithGuard(Action method)
{
if (HeadSize) method();
}
Then you could do this:
public void ScreenFirstShot()
{
executeWithGuard(() =>
{
// code here
});
}
public void ScreenSecondShot()
{
ExecuteWithGuard(() =>
{
// code here
});
}
public void CrazyUp()
{
ExecuteWithGuard(() =>
{
// code here
});
}
There's no less code doing this... in fact, there's probably more code, but it does allow you to not have to do a find/replace if your guard condition ever changes. I'd only suggest it as a last resort, though. It's very possible that your real problem is that you're doing your validation too far down the call tree. If you can do it at a higher level, you may save yourself from all of this validation.
ALSO
Have a look at the null object patttern. This pattern can be used in some special cases to prevent or simplify state checking.
ALSO (rev 2)
It's hard to know what your intent is since the question focuses on a specific solution, but if you're executing these methods sequentially, you can look at using the strategy pattern, and putting the check in your base strategy class.
From a "pattern" standpoint, though, this doesn't seem onerous to me. It seems perfectly reasonable to me to type:
if(!Size)
return;
You're explicitly handling the cases you want. In your case, this check is pretty specific to what you are working with, from what I can tell (from your original + edits). I'd personally choose a more obvious name, since it does seem a little strange (even in your original), and not completely obvious what's happening.
Even with AOP, you'd be adding some other information here on each method, to make sure your aspect was handled.
Maybe just use one method and an Enum with the values First, Second, Finished etc.? It's hard to tell because, apart from that one check, you don't say what is common. AOP could be a solution, but maybe not, since aspects are usually more general in their conceptional nature.
BTW, maybe choose a different naming for your samples in the future, this may offend some people. (Edited to match new naming)