Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do access modifiers affect performance?

Do access modifiers affect performance in C#?

like image 228
user606035 Avatar asked Feb 12 '11 06:02

user606035


People also ask

Why are access modifiers important?

Access modifiers are important because they make your code more maintainable and provide encapsulation. Using access modifiers, you can make fields read-only/write-only and have complete control over what other classes can and can't access. This makes code both more readable and less error prone.

What are the possible effects of adding private access modifier to a class?

Private access modifier allows the least accessibility with the private data members to be accessible only within the class. Modifiers limit the scope of data members like classes, constructors, methods, and variables and define the limit as to which classes or packages can access them.

How do these access modifiers affect inheritance?

Access modifiers do not prevent inheritance. Instead, access modifiers affect what you can and cannot see in the subclass. Those private members and attributes are still in your subclasses. Your subclasses just cannot access them directly.

Which access modifier is used mostly?

Access Modifier - private Therefore, the access modifier private is mostly used for fields, constructors and methods. A compile-time error is thrown, when trying to access in a different class even with in the same package. Example of private Class: A Class cannot have the private access modifier.


1 Answers

No, access modifiers are not considered by the runtime for execution. The only time they come into play after compilation is if you are using reflection and querying the assembly's metadata.

Think of access modifiers like concrete forms. They are put in place when the concrete is wet to provide form and boundaries for the wet concrete. Once the concrete is dry they are removed as they are no longer needed. Access modifiers are the concrete forms for your un-compiled code - once the code has been compiled the access modifiers are no longer a factor (even though they are part of the emitted IL).

Edit: Maybe "no longer a factor" is a little vague. What I mean is that it's the compiler's job to make sure that all access modifiers are properly honored and no violations occur. The runtime (at least Microsoft's CLR - other runtimes are free to implement this any way they see fit) trusts that the compiler has done its job and no further checks are necessary.

like image 56
Andrew Hare Avatar answered Oct 21 '22 22:10

Andrew Hare