Home > front end >  Does the partial type need to have same name as the namespace it is contained in?
Does the partial type need to have same name as the namespace it is contained in?

Time:10-15

I was told by a user on Stack Overflow that if I split the definition of a type via keyword partial, parts of a type must be defined within a namespace that has the same name as the type whose definition is split. Is that true?

namespace Car
{
   public partial Car { }
   public partial Car { }
}

CodePudding user response:

To answer your question: "if [you] split the definition of a type via keyword partial, parts of a type must be defined within a namespace that has the same name as the type whose definition is split. Is that true?", the answer is No.

The two (or more) halves of a partial type definition must have the same name. Since the full name of a type includes its assembly and its namespace, the namespaces must match. Typically, those two halves are in different files (one often wizard generated, and one managed by a programmer). So this is pretty typical:

In MyClass.cs:

namespace Name.Space {

    public partial class MyClass {
        // non-wizard-generated code 
    }
}

And in MyClass.designer.cs:

namespace Name.Space {

    public partial class MyClass {
        // wizard-generated code 
    }
}

If the class names or the namespace names don't match up (or if the two halves are in different assemblies), then you end up with two type definitions, not one (split over two files).

I think you misunderstood what was said

  • Related