473,703 Members | 2,542 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Passing in operators

Tem
I have 3 static methods that share almost the same code with only a few
lines where different operators are used.

Is there a way to pass in an operator as a parameter?

pseudo code

Greater() {Base(>)}
Less() {Base(<)}
Equal() {Base(==)}

Base(operator op)
{
....

if(a op b)
....
}

Or another way of doing this?

Tem

Jun 27 '08 #1
6 7551
Or another way of doing this?

Depending on what you are doing, you could use a delegate - i.e. a
Func<T,T,bool>; whether this is a good idea (or not) depends on the
scenario... easy enough in C# 3 with lambdas...

public static void Greater() {Base((x,y) =x y);}
public static void Less() {Base((x,y) =x < y);}
public static void Equal() {Base((x,y) =x == y);}

private static void Base(Func<Foo,F oo,boolop)
{
//...
if(op(a,b))
{
//...
}
}

(again: I stress hard to give a great answer without more info)

Marc
Jun 27 '08 #2
I should also add that for equaility (==, !=) an inequality (<, <=, >,
>=) you can also use EqualityCompare r<T>.Default and
Comparer<T>.Def ault to do a lot, without requiring direct access to
operators (actually it uses IComparable<Tan d IEquatable<T>).

Marc
Jun 27 '08 #3
"Tem" <te*****@yahoo. comwrote:
I have 3 static methods that share almost the same code with only a
few lines where different operators are used. Is there a way to pass
in an operator as a parameter?
What you can do is pass in a delegate (method pointer) that performs the
desired comparison, e.g.
delegate bool CompareDelegate (int x, int y);
static void Main()
{
CompareDelegate lessThan = delegate(int x, int y) { return x < y; };
CompareDelegate moreThan = delegate(int x, int y) { return x y; };

bool isLess = Compare(2, 5, lessThan); // true
bool isMore = Compare(2, 5, moreThan); // false
}
static bool Compare(int a, int b, CompareDelegate c)
{
return c(a, b);
}
Eq.
Jun 27 '08 #4
Tem
Thank you guys for the help. Now I see what delegates are useful for.

"Paul E Collins" <fi************ ******@CL4.orgw rote in message
news:l5******** *************** *******@bt.com. ..
"Tem" <te*****@yahoo. comwrote:
>I have 3 static methods that share almost the same code with only a few
lines where different operators are used. Is there a way to pass in an
operator as a parameter?

What you can do is pass in a delegate (method pointer) that performs the
desired comparison, e.g.
delegate bool CompareDelegate (int x, int y);
static void Main()
{
CompareDelegate lessThan = delegate(int x, int y) { return x < y; };
CompareDelegate moreThan = delegate(int x, int y) { return x y; };

bool isLess = Compare(2, 5, lessThan); // true
bool isMore = Compare(2, 5, moreThan); // false
}
static bool Compare(int a, int b, CompareDelegate c)
{
return c(a, b);
}
Eq.

Jun 27 '08 #5
Tem
Can this be written with lambda expressions?

"Paul E Collins" <fi************ ******@CL4.orgw rote in message
news:l5******** *************** *******@bt.com. ..
"Tem" <te*****@yahoo. comwrote:
>I have 3 static methods that share almost the same code with only a few
lines where different operators are used. Is there a way to pass in an
operator as a parameter?

What you can do is pass in a delegate (method pointer) that performs the
desired comparison, e.g.
delegate bool CompareDelegate (int x, int y);
static void Main()
{
CompareDelegate lessThan = delegate(int x, int y) { return x < y; };
CompareDelegate moreThan = delegate(int x, int y) { return x y; };

bool isLess = Compare(2, 5, lessThan); // true
bool isMore = Compare(2, 5, moreThan); // false
}
static bool Compare(int a, int b, CompareDelegate c)
{
return c(a, b);
}
Eq.

Jun 27 '08 #6
Can this be written with lambda expressions?

yes; I aleady posted a variant using lambdas (although using the
"delegate" version of a lambda*); using an actual Expression is
possible - not sure if it gains much, though (the delegate is likely
to be quicker than reflection from a PropertyInfo).

Whether this is the *best* approach depends largely on the full
scenario.

*=lambdas can be compiled to either a delegate or a System.Expressi on.

Marc
Jun 27 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

58
10150
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of code... TCHAR myArray; DoStuff(myArray);
25
2932
by: Victor Bazarov | last post by:
In the project I'm maintaining I've seen two distinct techniques used for returning an object from a function. One is AType function(AType const& arg) { AType retval(arg); // or default construction and then.. // some other processing and/or changing 'retval' return retval; }
32
5017
by: paul | last post by:
HI! I keep on getting this error and I have tried different things but I am not sure how to send the expiring date. The error that I am getting in Firefox 1.5 is "Error: expires.toGMTString is not a function" ---------------------------------------------------- I have this in a .js file and in the head section.
8
2099
by: Ivan Liu | last post by:
Hi, I'd like to ask if passing an object as an pointer into a function evokes the copy constructor. Ivan
0
9251
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9117
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9014
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8961
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7861
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5922
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3122
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2446
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2063
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.