Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# dictionary equality requirement

Do the keys of a Dictionary need to be comparable with equality?

For example

Class mytype
{
    public bool equals(mytype other)
    {
        return ...;
    }
}

In my case they won't be equal unless they are the same instance.

If I need to implement equality should I have a large numeric value that increments with every new instance of mytype created?

like image 495
alan2here Avatar asked Jan 06 '12 14:01

alan2here


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 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.

Why is C named so?

Quote from wikipedia: "A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix." The creators want that everyone "see" his language. So he named it "C".

What is C of computer?

" " C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use.


1 Answers

If your classes are only equal if they are same instance, then you don't need to do anything to use them in a Dictionary. Classes (reference types) are considered equal if and only if the refer to the same object.

From the documentation of GetHashCode

For derived classes of Object, the GetHashCode method can delegate to the Object.GetHashCode implementation, if and only if that derived class defines value equality to be reference equality and the type is not a value type.

Which seems to be true in your case. As a rule of thumb, if you override Equal you need to override GetHashCode as well but this is not necessary in your case as the default is what you are looking for.

like image 167
parapura rajkumar Avatar answered Sep 21 '22 06:09

parapura rajkumar