why in c# casting object to objects of type T with same value aren't recognized the same?











up vote
4
down vote

favorite












I am getting into generics but there is something I don't understand Here I have this class;



    class Node<T>{
T value;
Node <T> next,prev;
public Node(T vl)
{
this.value=vl;
this.next=this.prev=null;
}
}


I have a class List and a method Insert and it is working fine :



 class Lista<T>
{
public Node<T> Head, Tail;
public int Cnt;

public Lista()
{
this.Head = this.Tail = null;
this.Cnt = 0;
}



public void Insert(T vl)
{
Node<T> nd = new Node<T>(vl);
if (this.IsEmpty())
this.Head = this.Tail = nd;
else
{
this.Tail.next = nd;
nd.prev = this.Tail;
this.Tail = nd;
}
this.Cnt++;
}


}


but I Have a method FindNode:



 public Node<T> FindNode(T vl)
{
if (this.IsEmpty()) return null;
Node<T> tmp = this.Head;
while (tmp != null && ((object)tmp.VL != (object)vl)) tmp = tmp.next;
return tmp;
}


which finds a Node inside the List now the problem is
if I have a Lista<string> it works fine but if I create a Lista<int>
even if the element in list exists while comparing it is ignoring the same values and going next until it goes null , why does that happen ?



Method isEmpty:



public bool IsEmpty()
{
if (this.Head == null && this.Tail == null) return true;
return false;
}









share|improve this question


















  • 1




    Generics was invented to avoid something like (object)tmp.VL.
    – SeM
    Nov 22 at 17:36










  • You haven't overloaded Equals so how is C# going to know you consider them the same? It can only check whether the variables refer to the same instance
    – Panagiotis Kanavos
    Nov 22 at 17:36












  • @SeM I know right but if I say tmp.VL==vl it says that operand== cannot be used to types T and T
    – Johnny Adams
    Nov 22 at 17:38










  • @PanagiotisKanavos how do I do that could you explain please
    – Johnny Adams
    Nov 22 at 17:38










  • @JohnnyAdams instead of trying to cover up the compilation problem, fix it. Override Equals and ==
    – Panagiotis Kanavos
    Nov 22 at 17:39















up vote
4
down vote

favorite












I am getting into generics but there is something I don't understand Here I have this class;



    class Node<T>{
T value;
Node <T> next,prev;
public Node(T vl)
{
this.value=vl;
this.next=this.prev=null;
}
}


I have a class List and a method Insert and it is working fine :



 class Lista<T>
{
public Node<T> Head, Tail;
public int Cnt;

public Lista()
{
this.Head = this.Tail = null;
this.Cnt = 0;
}



public void Insert(T vl)
{
Node<T> nd = new Node<T>(vl);
if (this.IsEmpty())
this.Head = this.Tail = nd;
else
{
this.Tail.next = nd;
nd.prev = this.Tail;
this.Tail = nd;
}
this.Cnt++;
}


}


but I Have a method FindNode:



 public Node<T> FindNode(T vl)
{
if (this.IsEmpty()) return null;
Node<T> tmp = this.Head;
while (tmp != null && ((object)tmp.VL != (object)vl)) tmp = tmp.next;
return tmp;
}


which finds a Node inside the List now the problem is
if I have a Lista<string> it works fine but if I create a Lista<int>
even if the element in list exists while comparing it is ignoring the same values and going next until it goes null , why does that happen ?



Method isEmpty:



public bool IsEmpty()
{
if (this.Head == null && this.Tail == null) return true;
return false;
}









share|improve this question


















  • 1




    Generics was invented to avoid something like (object)tmp.VL.
    – SeM
    Nov 22 at 17:36










  • You haven't overloaded Equals so how is C# going to know you consider them the same? It can only check whether the variables refer to the same instance
    – Panagiotis Kanavos
    Nov 22 at 17:36












  • @SeM I know right but if I say tmp.VL==vl it says that operand== cannot be used to types T and T
    – Johnny Adams
    Nov 22 at 17:38










  • @PanagiotisKanavos how do I do that could you explain please
    – Johnny Adams
    Nov 22 at 17:38










  • @JohnnyAdams instead of trying to cover up the compilation problem, fix it. Override Equals and ==
    – Panagiotis Kanavos
    Nov 22 at 17:39













up vote
4
down vote

favorite









up vote
4
down vote

favorite











I am getting into generics but there is something I don't understand Here I have this class;



    class Node<T>{
T value;
Node <T> next,prev;
public Node(T vl)
{
this.value=vl;
this.next=this.prev=null;
}
}


I have a class List and a method Insert and it is working fine :



 class Lista<T>
{
public Node<T> Head, Tail;
public int Cnt;

public Lista()
{
this.Head = this.Tail = null;
this.Cnt = 0;
}



public void Insert(T vl)
{
Node<T> nd = new Node<T>(vl);
if (this.IsEmpty())
this.Head = this.Tail = nd;
else
{
this.Tail.next = nd;
nd.prev = this.Tail;
this.Tail = nd;
}
this.Cnt++;
}


}


but I Have a method FindNode:



 public Node<T> FindNode(T vl)
{
if (this.IsEmpty()) return null;
Node<T> tmp = this.Head;
while (tmp != null && ((object)tmp.VL != (object)vl)) tmp = tmp.next;
return tmp;
}


which finds a Node inside the List now the problem is
if I have a Lista<string> it works fine but if I create a Lista<int>
even if the element in list exists while comparing it is ignoring the same values and going next until it goes null , why does that happen ?



Method isEmpty:



public bool IsEmpty()
{
if (this.Head == null && this.Tail == null) return true;
return false;
}









share|improve this question













I am getting into generics but there is something I don't understand Here I have this class;



    class Node<T>{
T value;
Node <T> next,prev;
public Node(T vl)
{
this.value=vl;
this.next=this.prev=null;
}
}


I have a class List and a method Insert and it is working fine :



 class Lista<T>
{
public Node<T> Head, Tail;
public int Cnt;

public Lista()
{
this.Head = this.Tail = null;
this.Cnt = 0;
}



public void Insert(T vl)
{
Node<T> nd = new Node<T>(vl);
if (this.IsEmpty())
this.Head = this.Tail = nd;
else
{
this.Tail.next = nd;
nd.prev = this.Tail;
this.Tail = nd;
}
this.Cnt++;
}


}


but I Have a method FindNode:



 public Node<T> FindNode(T vl)
{
if (this.IsEmpty()) return null;
Node<T> tmp = this.Head;
while (tmp != null && ((object)tmp.VL != (object)vl)) tmp = tmp.next;
return tmp;
}


which finds a Node inside the List now the problem is
if I have a Lista<string> it works fine but if I create a Lista<int>
even if the element in list exists while comparing it is ignoring the same values and going next until it goes null , why does that happen ?



Method isEmpty:



public bool IsEmpty()
{
if (this.Head == null && this.Tail == null) return true;
return false;
}






c# generics






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 at 17:33









Johnny Adams

276




276








  • 1




    Generics was invented to avoid something like (object)tmp.VL.
    – SeM
    Nov 22 at 17:36










  • You haven't overloaded Equals so how is C# going to know you consider them the same? It can only check whether the variables refer to the same instance
    – Panagiotis Kanavos
    Nov 22 at 17:36












  • @SeM I know right but if I say tmp.VL==vl it says that operand== cannot be used to types T and T
    – Johnny Adams
    Nov 22 at 17:38










  • @PanagiotisKanavos how do I do that could you explain please
    – Johnny Adams
    Nov 22 at 17:38










  • @JohnnyAdams instead of trying to cover up the compilation problem, fix it. Override Equals and ==
    – Panagiotis Kanavos
    Nov 22 at 17:39














  • 1




    Generics was invented to avoid something like (object)tmp.VL.
    – SeM
    Nov 22 at 17:36










  • You haven't overloaded Equals so how is C# going to know you consider them the same? It can only check whether the variables refer to the same instance
    – Panagiotis Kanavos
    Nov 22 at 17:36












  • @SeM I know right but if I say tmp.VL==vl it says that operand== cannot be used to types T and T
    – Johnny Adams
    Nov 22 at 17:38










  • @PanagiotisKanavos how do I do that could you explain please
    – Johnny Adams
    Nov 22 at 17:38










  • @JohnnyAdams instead of trying to cover up the compilation problem, fix it. Override Equals and ==
    – Panagiotis Kanavos
    Nov 22 at 17:39








1




1




Generics was invented to avoid something like (object)tmp.VL.
– SeM
Nov 22 at 17:36




Generics was invented to avoid something like (object)tmp.VL.
– SeM
Nov 22 at 17:36












You haven't overloaded Equals so how is C# going to know you consider them the same? It can only check whether the variables refer to the same instance
– Panagiotis Kanavos
Nov 22 at 17:36






You haven't overloaded Equals so how is C# going to know you consider them the same? It can only check whether the variables refer to the same instance
– Panagiotis Kanavos
Nov 22 at 17:36














@SeM I know right but if I say tmp.VL==vl it says that operand== cannot be used to types T and T
– Johnny Adams
Nov 22 at 17:38




@SeM I know right but if I say tmp.VL==vl it says that operand== cannot be used to types T and T
– Johnny Adams
Nov 22 at 17:38












@PanagiotisKanavos how do I do that could you explain please
– Johnny Adams
Nov 22 at 17:38




@PanagiotisKanavos how do I do that could you explain please
– Johnny Adams
Nov 22 at 17:38












@JohnnyAdams instead of trying to cover up the compilation problem, fix it. Override Equals and ==
– Panagiotis Kanavos
Nov 22 at 17:39




@JohnnyAdams instead of trying to cover up the compilation problem, fix it. Override Equals and ==
– Panagiotis Kanavos
Nov 22 at 17:39












1 Answer
1






active

oldest

votes

















up vote
4
down vote



accepted










The problem is, that for valuetypes like int in your example you are boxing them by casting to object.
Per default, the == operator does ReferenceEquality and this means that it will never return true in your case.



Easiest was to fix this would be to turn this line



while (tmp != null && ((object)tmp.VL != (object)vl)) tmp = tmp.next;


into this



 while (tmp != null && !Equals(tmp.VL , vl)) tmp = tmp.next;


This will use the default equality comparer for a certain type and makes your code work as intended.



you could go further and make and fix by using a generic constraint declared for your class like so:



class Lista<T> where T : IEquateable<T>


and change the same line like this



while (tmp != null && (!tmp.VL.Equals(vl)) tmp = tmp.next;


Or make it possible to inject an IEqualityComparer<T> into your class



  class Lista<T>
{
IEqualityComparer<T> _comparer;
public Lista(IEqualityComparer<T> comparer = null)
{
_comparer = comparer ?? EuqlityComparer<T>.Default;
}

public Node<T> FindNode(T vl)
{
if (this.IsEmpty()) return null;
Node<T> tmp = this.Head;
while (tmp != null && !_comparer.Equals(tmp.VL, vl) tmp = tmp.next;
return tmp;
}
}





share|improve this answer























  • thanks this was simple and worked like charm , but from the both methods you suggested which one would you recommend to use
    – Johnny Adams
    Nov 22 at 17:47






  • 1




    @JohnnyAdams the last one, using the IEqualityComparer is usually common practice. But if you dont need it, the first one is just fine.
    – CSharpie
    Nov 22 at 17:47












  • okay thanks for your answer
    – Johnny Adams
    Nov 22 at 17:49











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53435912%2fwhy-in-c-sharp-casting-object-to-objects-of-type-t-with-same-value-arent-recogn%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
4
down vote



accepted










The problem is, that for valuetypes like int in your example you are boxing them by casting to object.
Per default, the == operator does ReferenceEquality and this means that it will never return true in your case.



Easiest was to fix this would be to turn this line



while (tmp != null && ((object)tmp.VL != (object)vl)) tmp = tmp.next;


into this



 while (tmp != null && !Equals(tmp.VL , vl)) tmp = tmp.next;


This will use the default equality comparer for a certain type and makes your code work as intended.



you could go further and make and fix by using a generic constraint declared for your class like so:



class Lista<T> where T : IEquateable<T>


and change the same line like this



while (tmp != null && (!tmp.VL.Equals(vl)) tmp = tmp.next;


Or make it possible to inject an IEqualityComparer<T> into your class



  class Lista<T>
{
IEqualityComparer<T> _comparer;
public Lista(IEqualityComparer<T> comparer = null)
{
_comparer = comparer ?? EuqlityComparer<T>.Default;
}

public Node<T> FindNode(T vl)
{
if (this.IsEmpty()) return null;
Node<T> tmp = this.Head;
while (tmp != null && !_comparer.Equals(tmp.VL, vl) tmp = tmp.next;
return tmp;
}
}





share|improve this answer























  • thanks this was simple and worked like charm , but from the both methods you suggested which one would you recommend to use
    – Johnny Adams
    Nov 22 at 17:47






  • 1




    @JohnnyAdams the last one, using the IEqualityComparer is usually common practice. But if you dont need it, the first one is just fine.
    – CSharpie
    Nov 22 at 17:47












  • okay thanks for your answer
    – Johnny Adams
    Nov 22 at 17:49















up vote
4
down vote



accepted










The problem is, that for valuetypes like int in your example you are boxing them by casting to object.
Per default, the == operator does ReferenceEquality and this means that it will never return true in your case.



Easiest was to fix this would be to turn this line



while (tmp != null && ((object)tmp.VL != (object)vl)) tmp = tmp.next;


into this



 while (tmp != null && !Equals(tmp.VL , vl)) tmp = tmp.next;


This will use the default equality comparer for a certain type and makes your code work as intended.



you could go further and make and fix by using a generic constraint declared for your class like so:



class Lista<T> where T : IEquateable<T>


and change the same line like this



while (tmp != null && (!tmp.VL.Equals(vl)) tmp = tmp.next;


Or make it possible to inject an IEqualityComparer<T> into your class



  class Lista<T>
{
IEqualityComparer<T> _comparer;
public Lista(IEqualityComparer<T> comparer = null)
{
_comparer = comparer ?? EuqlityComparer<T>.Default;
}

public Node<T> FindNode(T vl)
{
if (this.IsEmpty()) return null;
Node<T> tmp = this.Head;
while (tmp != null && !_comparer.Equals(tmp.VL, vl) tmp = tmp.next;
return tmp;
}
}





share|improve this answer























  • thanks this was simple and worked like charm , but from the both methods you suggested which one would you recommend to use
    – Johnny Adams
    Nov 22 at 17:47






  • 1




    @JohnnyAdams the last one, using the IEqualityComparer is usually common practice. But if you dont need it, the first one is just fine.
    – CSharpie
    Nov 22 at 17:47












  • okay thanks for your answer
    – Johnny Adams
    Nov 22 at 17:49













up vote
4
down vote



accepted







up vote
4
down vote



accepted






The problem is, that for valuetypes like int in your example you are boxing them by casting to object.
Per default, the == operator does ReferenceEquality and this means that it will never return true in your case.



Easiest was to fix this would be to turn this line



while (tmp != null && ((object)tmp.VL != (object)vl)) tmp = tmp.next;


into this



 while (tmp != null && !Equals(tmp.VL , vl)) tmp = tmp.next;


This will use the default equality comparer for a certain type and makes your code work as intended.



you could go further and make and fix by using a generic constraint declared for your class like so:



class Lista<T> where T : IEquateable<T>


and change the same line like this



while (tmp != null && (!tmp.VL.Equals(vl)) tmp = tmp.next;


Or make it possible to inject an IEqualityComparer<T> into your class



  class Lista<T>
{
IEqualityComparer<T> _comparer;
public Lista(IEqualityComparer<T> comparer = null)
{
_comparer = comparer ?? EuqlityComparer<T>.Default;
}

public Node<T> FindNode(T vl)
{
if (this.IsEmpty()) return null;
Node<T> tmp = this.Head;
while (tmp != null && !_comparer.Equals(tmp.VL, vl) tmp = tmp.next;
return tmp;
}
}





share|improve this answer














The problem is, that for valuetypes like int in your example you are boxing them by casting to object.
Per default, the == operator does ReferenceEquality and this means that it will never return true in your case.



Easiest was to fix this would be to turn this line



while (tmp != null && ((object)tmp.VL != (object)vl)) tmp = tmp.next;


into this



 while (tmp != null && !Equals(tmp.VL , vl)) tmp = tmp.next;


This will use the default equality comparer for a certain type and makes your code work as intended.



you could go further and make and fix by using a generic constraint declared for your class like so:



class Lista<T> where T : IEquateable<T>


and change the same line like this



while (tmp != null && (!tmp.VL.Equals(vl)) tmp = tmp.next;


Or make it possible to inject an IEqualityComparer<T> into your class



  class Lista<T>
{
IEqualityComparer<T> _comparer;
public Lista(IEqualityComparer<T> comparer = null)
{
_comparer = comparer ?? EuqlityComparer<T>.Default;
}

public Node<T> FindNode(T vl)
{
if (this.IsEmpty()) return null;
Node<T> tmp = this.Head;
while (tmp != null && !_comparer.Equals(tmp.VL, vl) tmp = tmp.next;
return tmp;
}
}






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 22 at 17:50

























answered Nov 22 at 17:38









CSharpie

6,17623352




6,17623352












  • thanks this was simple and worked like charm , but from the both methods you suggested which one would you recommend to use
    – Johnny Adams
    Nov 22 at 17:47






  • 1




    @JohnnyAdams the last one, using the IEqualityComparer is usually common practice. But if you dont need it, the first one is just fine.
    – CSharpie
    Nov 22 at 17:47












  • okay thanks for your answer
    – Johnny Adams
    Nov 22 at 17:49


















  • thanks this was simple and worked like charm , but from the both methods you suggested which one would you recommend to use
    – Johnny Adams
    Nov 22 at 17:47






  • 1




    @JohnnyAdams the last one, using the IEqualityComparer is usually common practice. But if you dont need it, the first one is just fine.
    – CSharpie
    Nov 22 at 17:47












  • okay thanks for your answer
    – Johnny Adams
    Nov 22 at 17:49
















thanks this was simple and worked like charm , but from the both methods you suggested which one would you recommend to use
– Johnny Adams
Nov 22 at 17:47




thanks this was simple and worked like charm , but from the both methods you suggested which one would you recommend to use
– Johnny Adams
Nov 22 at 17:47




1




1




@JohnnyAdams the last one, using the IEqualityComparer is usually common practice. But if you dont need it, the first one is just fine.
– CSharpie
Nov 22 at 17:47






@JohnnyAdams the last one, using the IEqualityComparer is usually common practice. But if you dont need it, the first one is just fine.
– CSharpie
Nov 22 at 17:47














okay thanks for your answer
– Johnny Adams
Nov 22 at 17:49




okay thanks for your answer
– Johnny Adams
Nov 22 at 17:49


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53435912%2fwhy-in-c-sharp-casting-object-to-objects-of-type-t-with-same-value-arent-recogn%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Trompette piccolo

Slow SSRS Report in dynamic grouping and multiple parameters

Simon Yates (cyclisme)