Home > Back-end >  Disable implicit conversion of third party classes in C# without writing wrappers?
Disable implicit conversion of third party classes in C# without writing wrappers?

Time:02-24

I use an engine which got Vector3 and Vector2 classes.

However there are regular issues by accidentally passing a Vector2 to a method which needs a Vector3.

Currently it's automatically converted to a Vector3 of (x, y, 0). After I experience runtime issues it always takes some time to I find these trivial causes...

Is it possible to somehow block the implicit conversion between these two third party classes so I can detect these problems at compile time?

Currently my only idea is to write wrappers and replace every usage of Vector3 and Vector2 with them.

But it seems tedious. Is there any other way?

CodePudding user response:

You could create a custom code analyzer and configure it to cause a compile-time error whenever this implicit conversion happens in your code.

See https://docs.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix for a tutorial.

If you do this, you could also put that analyzer into a Nuget package so other people using the same third-party library can benefit from the work you've done.

CodePudding user response:

I suppose that Vector3 class has this code:

public static implicit operator Vector3(Vector2 vector) => new Vector3(vector.x, vector.y, 0);

Unfortunately, you cannot block the conversion (C# built-in feature). Honestly, it is a poor design choice made by the Engine designers...

You can only create your own wrappers to overcome this issue.

public class Vector2Ex {
  public Vector2 vector2 { get; set; }
}
  • Related