Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial classes and access modifier issue

According to MSDN Documentation for partial classes :

All the parts must have the same accessibility, such as public, private, and so on.

but if you create a WindowsForm application, you will have the default Form class in two partial classes.

The code behind :

public partial class Form1 : Form
{
    ...
}

and the designer :

partial class Form1
{
    ...
}

Access modifiers are different, but it will compile.

Am I missing something here?

like image 277
Naser Asadi Avatar asked Aug 20 '14 07:08

Naser Asadi


People also ask

What will happen if there is an implementation of partial method without defining partial?

Similar to a partial class, a partial method can be used as a definition in one part while another part can be the implementation. If there is no implementation of the partial method then the method and its calls are removed at compile time. Compiler compiles all parts of a partial method to a single method.

What will happen when a property of a class has no access modifier?

If a variable/method is defined without any access modifier keyword, then that will have a default modifier access. Visible to All classes. Visible to classes with in the package and the subclasses of other package.

Can we use access modifiers with class?

The protected access modifier is accessible within package and outside the package but through inheritance only. The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.

Do partial classes have to be in same namespace?

All parts of a partial class should be in the same namespace. Each part of a partial class should be in the same assembly or DLL, in other words you can't create a partial class in source files of a different class library project. Each part of a partial class has the same accessibility.


1 Answers

If you don't specify the access modifier in a part of a partial class, it uses the same access modifier as the other part.


Relevant part from the C# 5 spec: §10.2.2

When a partial type declaration includes an accessibility specification (the public, protected, internal, and private modifiers) it must agree with all other parts that include an accessibility specification. If no part of a partial type includes an accessibility specification, the type is given the appropriate default accessibility (§3.5.1).

So the spec says that the accessibility must agree with other parts if it is specified; in other words, it doesn't have to be specified in every part. The wording could probably be changed to be less ambiguous, though...

like image 50
Thomas Levesque Avatar answered Oct 06 '22 01:10

Thomas Levesque