Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c#: Actions incomparable?

I'm trying to compare two Actions. The comparison with == always returns false as does the Equals-method even though it's the same instance.

My question is: Is it really not possible or am I doing it wrong?

Cheers AC

like image 263
Anonymous Coward Avatar asked Mar 29 '11 09:03

Anonymous Coward


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.


2 Answers

You are doing it wrong.

If I am to believe you, when you say "even though it's the same instance", then the following code executed through LINQPad tells me that you must be doing something wrong, or the "same instance" is incorrect:

void Main()
{
    Action a = () => Debug.WriteLine("test");
    Action b = a;

    (a == b).Dump("==");
    (a.Equals(b)).Dump("Equals");
    object.ReferenceEquals(a, b).Dump("ReferenceEquals");
}

The output is:

== 
True 

Equals 
True 

ReferenceEquals 
True

In other words, both ==, a.Equals(b) and object.ReferenceEquals(a, b) says its the same instance.

On the other hand, if I duplicate the code:

Action a = () => Debug.WriteLine("test");
Action b = () => Debug.WriteLine("test");

Then they all report false.

If I link them both to a named method, and not an anonymous one:

void Main()
{
    Action a = Test;
    Action b = Test;

    (a == b).Dump("==");
    (a.Equals(b)).Dump("Equals");
    object.ReferenceEquals(a, b).Dump("ReferenceEquals");
}

private static void Test()
{
}

Then the output is:

== 
True 

Equals 
True 

ReferenceEquals 
False

In other words, I now got two Action instances, not just one, but they still compare equal.

like image 150
Lasse V. Karlsen Avatar answered Sep 30 '22 00:09

Lasse V. Karlsen


You can compare Method and Target properties.

like image 38
Andrey Avatar answered Sep 30 '22 00:09

Andrey