
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
Encapsulation in C#
Encapsulation in C# prevents access to implementation details. Implement Encapsulation in C# using access specifiers.
The following are the access specifiers supported by C#.
- Public
- Private
- Protected
- Internal
- Protected internal
Encapsulation can be understood by taking an example of private access specifier that allows a class to hide its member variables and member functions from other functions and objects.
In the following example we have length and width as variables assigned private access specifier.
Example
using System; namespace RectangleApplication { class Rectangle { private double length; private double width; public void Acceptdetails() { length = 10; width = 15; } public double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } } class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.Acceptdetails(); r.Display(); Console.ReadLine(); } } }
Output
Length: 10 Width: 15 Area: 150
- Related Articles
- Encapsulation in C++
- What is encapsulation in C#?
- How is encapsulation implemented in C#?
- Encapsulation in Java
- Explain Encapsulation in PHP.
- IP-in-IP Encapsulation
- What is encapsulation in Java?
- Abstraction vs Encapsulation in Java
- Advantages of encapsulation in Java
- What is Encapsulation in Python?
- How Does Encapsulation Work in Ruby?
- Golang Program to Show Encapsulation in Class
- JavaScript Encapsulation using Anonymous Functions
- Difference Between Abstraction and Encapsulation
- Difference between encapsulation and decapsulation

Advertisements