Domanda

I would like to create an extension method for the System.Array class that will take in a char[] or byte[] array and return its Length. I need this method for in case the array is null, and I don't want to litter the code with whole bunch of (arr == null) ? 0 : arr.Length calls.

I want to call it like this: Array.ReturnLength(arr).

I tried implementing it, but I only see it when I do arr.ReturnLength(), but not as an Array method.

public static int ReturnLength(this Array arr)
{
    if (arr == null)
        return 0;
    return arr.Length;
}

Any ideas? Thanks.

È stato utile?

Soluzione

You could use a generic extension method:

public static int ReturnLength<T>(this T[] arr)
{
    if (arr == null)
        return 0;
    return arr.Length;
}

You can use it with a null reference:

string[] arr = null;
int length = arr.ReturnLength(); // 0

Update: but your non generic extension method should work the same way:

public static int ReturnLength(this Array arr)
{
    if (arr == null)
        return 0;
    return arr.Length;
}

This works because extension methods are just syntactic sugar. Actually they are static methods which you could also use via class name:

int length = MyExtensions.ReturnLength(arr);

In C#, what happens when you call an extension method on a null object?

Altri suggerimenti

As explained in the comments, C# doesn't allow for static extension methods. However, extension methods are just syntactic sugar, and you are allowed to call them as static methods off of the class they are defined in, rather than instance methods off of the object they are defined on.

You already know you can call your method via arr.ReturnLength(). You can also call it via MyExtensionsClass.ReturnLength(arr), where MyExtensionsClass is the static class in which ReturnLength is defined.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top