Home > Mobile >  Compiler does not recognize original methods of system class after creating a partial of named class
Compiler does not recognize original methods of system class after creating a partial of named class

Time:02-27

I created this, a short simple function, that should describe my problem:

namespace System
{
    public abstract partial class Array
    {
        public static TElement[] Single<TElement>(TElement element)
        {
            return new[] { element };
        }
    }
}

The problem, that I have, is now my solution does not recognize the original functions and methods of the Array class.

Example: Array.IndexOf(elements, element)

I checked the source code visible through my IDE, where the Array class indeed has a partial keyword:

namespace System
{
    [Serializable]
    [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
    public abstract partial class Array : ICloneable, IList, IStructuralComparable, IStructuralEquatable
    {
    }
}

I'm a little confused, since by my logic this should work.

BUT

I also checked the Array class from Microsoft documentation page, where the partial keyword was missing.

What am I doing wrong and how can I fix this?
Is this a documentation problem and the Array class is actually not partial?

CodePudding user response:

Partial classes don't work like that. You can't add bits to an existing class in a different assembly.

Partial classes allow the source code for a single type in your project to be split across multiple source files. They don't allow for the types themselves to be split between assemblies.

It wouldn't make sense for documentation to show the partial keyword because it's an implementation detail. By the time the code is compiled, there's basically no difference between a type that was implemented using partial and one that had all the same code in one source file.

It sounds like what you really want is sort of "static extensions" - I believe this has been considered as a feature of C#, but I don't know whether it's actually coming any time soon.

CodePudding user response:

You cannot do what you are trying to do. 'partial' classes are to allow you to split the source code over several files. You dont have the source of System.Array.

What you ended up with was a thing called System.Array that replaced the standard one. Hence the 'loss' of all the other methods

What you are looking for are extension methods, if thats what you are trying to do. ie add new functions to Array objects. As JOn Skeet points out, it looks like you are trying to add new static methods to System.Array, extensions cant do that; only instance methods

  • Related