Henry Aung
Henry Aung

Reputation: 672

Combine Partial Classes with Normal Classes

Is it possible to combine a normal class with a partial class like this:

public class ClassA
{
    public string PropertyA {get; set;}
}

public partial class ClassA
{
    public string PropertyB {get; set;}
}

The result of the code should look:

var instance = new ClassA();

instance.PropertyA = "Something";
instance.PropertyB = "Something else";

Does C# support this pattern?

Thank you all in advance!

Upvotes: 1

Views: 760

Answers (3)

moribvndvs
moribvndvs

Reputation: 42497

All files partaking in partial on a class must be define the class with partial. Furthermore, they must exist in the same assembly.

You could use polymorphism to extend ClassA. There are also extension methods, but as the name states, you can only extend methods.

Here is derivative class, although its not at all the same as partial.

public class ClassA
{

    public string PropertyA { get; set; }
}

public class ClassB : ClassA
{
    public string PropertyB { get; set; }
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500873

No. All parts of a partial class have to include the partial modifier. From section 10.2 of the C# 4 language specification:

Each part of a partial type declaration must include a partial modifier. It must have the same name and be declared in the same namespace or type declaration as the other parts. The partial modifier indicates that additional parts of the type declaration may exist elsewhere, but the existence of such additional parts is not a requirement; it is valid for a type with a single declaration to include the partial modifier.

All parts of a partial type must be compiled together such that the parts can be merged at compile-time into a single type declaration. Partial types specifically do not allow already compiled types to be extended.

(Emphasis mine.)

Upvotes: 2

Philip Daubmeier
Philip Daubmeier

Reputation: 14934

Short answer: No. The MSDN states here:

All the parts must use the partial keyword. All of the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as public, private, and so on.

Upvotes: 4

Related Questions