Home > Net >  How to accept objects of multiple types in C# function?
How to accept objects of multiple types in C# function?

Time:11-16

Right now I have two functions:

public void func(Unity.Collections.NativeArray<ushort> a){}

public void func(Unity.Collections.NativeArray<short> a){}

The functions are the exact same besides the object datatype input. I am also not writing to these NativeArrays, so the code functions identically whether it is reading the array as <ushort> or <short>. Is there a way to combine these into one function that can accept both types of objects? NativeArrays are a managed type, so I can't use pointers. Any other ways to avoid duplicating the whole function or duplicating the objects?

CodePudding user response:

public void func<T>(Unity.Collections.NativeArray<T> a) where T : struct
{}

perhaps adding any constraints that NativeArray<T> requires, such as where T : struct or where T : unmanaged (I found and edited for this; the T : struct is the relevant one)

Note that until C# 11 / .NET 7, operators (math etc) and generics are a pain to work with together, so if you're summing/averaging etc based on the values: that might be hard.

CodePudding user response:

The function is a custom implementation of a blur function. So all it does is smooth the values. It doesn't care where zero is; as long as the numbers are all 2 bytes.

In that case, then, I wonder if what you really want is: spans.

Consider:

public void func(Unity.Collections.NativeArray<ushort> a)
  => func(MemoryMarshal.Cast<ushort, short>(a.AsSpan()));

public void func(Unity.Collections.NativeArray<short> a)
  => func(a.AsSpan());

private void func(Span<short> a)
{ ... real code here ...}

which uses Span<short> for the real code, and reinterprets the ushort version to use the short code - allowing you to work with the values without copying / casting the values individually

  • Related