0

I am porting a C# struct over to VB.NET and am facing the following problem:

The struct is used to safely invoke methods on objects without the need to check for null all the time. It has exactly one generic member, which can be null:

mValue As T

The GetHashCode method is implemented like that:

public override int GetHashCode()
{
    if (this.mValue != null)
    {
        this.mValue.GetHashCode();
    }

    return base.GetHashCode();
}

In the VB.NET implementation I cannot do

Return MyBase.GetHashCode()

because MyBase is not valid within a structure.

I have read this comment on how ValueType.GetHashCode is implemented.

According to this, in my example, I could probably just use

Return Me.GetType().GetHashCode()

for the case where mValue is null.

But this does not seem like a very solid implementation to me. Is there some simple way to call base.GetHashCode() for a structure in VB.NET?

Silvan
  • 1
  • 1
  • 4
    What would you expect `base.GetHashCode()` to return anyway? Shouldn't you return the same hash code for every value that has a null value for `mValue`? Why not just return 0? – Jon Skeet Dec 17 '18 at 10:12
  • You should be able to simply cast the current instance as `ValueType` or `Object`, e.g. `Return DirectCast(Me, ValueType).GetHashCode()`. – jmcilhinney Dec 17 '18 at 10:15
  • See msdn : https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/objects-and-classes/inheritance-basics – jdweng Dec 17 '18 at 10:23
  • @jmcilhinney: This will result in a stack overflow because it will call its own *GetHashCode* method indefinitely. – Silvan Dec 17 '18 at 12:13
  • @JonSkeet: Good question, I did not think about that in much detail. I just wanted the same behaviour as the C# implementation because I have to replace it with my VB.NET implementation of said struct. – Silvan Dec 17 '18 at 12:16
  • It is not often that vb.net forces you to stop relying on a [bad practice](https://stackoverflow.com/a/5927853/17034) :). That link tells you how to get the C# behavior back, pick the first field in the struct that is non-null and return its GetHashCode() value. – Hans Passant Dec 17 '18 at 12:56
  • Thank you @HansPassant for the link, that is an interesting read. – Silvan Dec 17 '18 at 17:24

0 Answers0