Cheung
Cheung

Reputation: 15552

Inherits the access modifiers?

Assume i have a class:

public class Products
{
    public string ID { get; set; }
    public string Name { get; set; }

    public string GetItemName() {  ... }
    public void SetItemName() {  ... }
    public string GetItemID() {  ... }
    public void SetItemID() {  ... }

    //...
}

It is any way to make all the properties or method inherits the parent class's access modifiers,so i don't have to assign [public] to each of properties/method.

Upvotes: 0

Views: 624

Answers (3)

Arjan Einbu
Arjan Einbu

Reputation: 13672

No, the language specs say that if you don't specify the access modifier, a default one will be used:

  • Members in classes and structs are private by default.
  • Types (classes, structs, delegates, interfaces and enums) are internal by default, unless they are placed within another type (nested classes) when they default to private..
  • Interface members, enum members and namespaces have no concept of accessibility modifiers, but can be thought of as always being public.

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 941237

public string Name { get; set; }
public string GetItemName() {  ... }
public void SetItemName() {  ... }

That's not C# code, that's C++. A language that doesn't support properties, but does support this:

public:
    string GetItemName();
    void SetItemName();

Which is probably what you are really asking for. No, never make the mistake of comparing C# to C++, it resembles the language only in passing. The accessor keyword must be applied to every member. Good thing is, you'll have a lot less of them. Delete the GetItemName and SetItemName methods, the Name property is all you need.

Here's an old magazine article that might be useful to you, "C++ -> C#: What You Need to Know to Move from C++ to C#"

Upvotes: 1

0lukasz0
0lukasz0

Reputation: 3267

There is no way to do this with class. It's how C# syntax is defined. If you skip access modifier then the default value is applied, for classes it would be internal modifier and for their members private.

Other default values according to specification are:

  • Interfaces, like classes, can be declared as public or internal types. Unlike classes, interfaces default to internal access. Interface members are always public, and no access modifiers can be applied.

  • Namespaces and enumeration members are always public, and no access modifiers can be applied.

  • Delegates have internal access by default.

  • Any types declared within a namespace or at the top level of a compilation unit (for example, not within a namespace, class, or struct) are internal by default, but can be made public.

Upvotes: 0

Related Questions