简体   繁体   中英

What is max number of valid modifiers you can have while declaring a class in c#?

This question is more for curiosity.

By modifiers I mean, keywords that you add before declaring a class.

eg

//1       2        3             
public abstract partial class Foo
{

}

This have 3 modifiers public , abstract , and partial .

Zero modifiers, in this question perspective, would be something like

class Foo
{

}

What is the max number of valid modifiers you can have before the name of the class when declaring it?

The maximum number is...

5!

(or 6 if you count unsafe )

According to here , a class declaration looks like this:

class_declaration
    : attributes? class_modifier* 'partial'? 'class' identifier type_parameter_list?
      class_base? type_parameter_constraints_clause* class_body ';'?
    ;

You probably don't count the attributes as "modifiers", but you probably would count the partial keyword as a "class modifier", though it is not an actual class_modifier .

The list of class_modifier is:

class_modifier
    : 'new'
    | 'public'
    | 'protected'
    | 'internal'
    | 'private'
    | 'abstract'
    | 'sealed'
    | 'static'
    | class_modifier_unsafe
    ;

We know the longest access modifier is protected internal , so we can ignore all the access modifiers:

class_modifier
    : 'new'
    | 'abstract'
    | 'sealed'
    | 'static'
    | class_modifier_unsafe
    ;

You can only choose one of sealed , static and abstract , so we are left with 6 "keywords":

  • protected
  • internal
  • new
  • sealed / static / abstract
  • partial
  • unsafe

Note that new and protected internal can only be used in nested class declarations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM