Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects," which can contain data in the form of fields (often known as attributes or properties) and code in the form of procedures (often known as methods). C# is a fully object-oriented language, which means it supports the principles of OOP:
Classes and Objects in C#
Classes and objects are fundamental concepts in Object-Oriented Programming (OOP). In C#, a class is a blueprint for creating objects. It defines a type by bundling data and methods that work on the data into one single unit. An object, on the other hand, is an instance of a class.
Class
A class is a user-defined blueprint or prototype from which objects are created. It represents a group of similar objects. A class can contain fields, methods, properties, constructors, and other class members.
Defining a Class
public class Person
{
// Fields
private string name;
private int age;
// Constructor
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
// Properties
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get { return age; }
set
{
if (value >= 0)
{
age = value;
}
}
}
// Method
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
}
Object
An object is an instance of a class. When a class is defined, no memory is allocated until an object of that class is created. Objects can access the fields and methods defined in their class.
Creating an Object
public class Program
{
public static void Main(string[] args)
{
// Creating objects of the Person class
Person person1 = new Person("Alice", 30);
Person person2 = new Person("Bob", 25);
// Accessing properties and methods
person1.DisplayInfo(); // Output: Name: Alice, Age: 30
person2.DisplayInfo(); // Output: Name: Bob, Age: 25
// Modifying properties
person1.Age = 31;
person1.DisplayInfo(); // Output: Name: Alice, Age: 31
}
}
Components of a Class
Fields: Variables that hold data for the class.
private string name;
private int age;
Properties: Provide a way to read, write, or compute the values of private fields. They are public by default.
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get { return age; }
set
{
if (value >= 0)
{
age = value;
}
}
}
Methods: Functions that perform actions. They define the behavior of the class.
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
Constructors: Special methods that are called when an object is instantiated. They initialize the fields of the class.
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
Access Modifiers
Access modifiers define the accessibility of the class members. The most common access modifiers in C# are:
Summary
Encapsulation is the bundling of data and methods that operate on the data into a single unit or class, and restricting access to some of the object's components.
Key Concepts:
Example: Encapsulation with a Person Class
Let's create a Person class that encapsulates the properties Name and Age.
public class Person
{
// Private fields
private string _name;
private int _age;
// Public property for Name with a getter and setter
public string Name
{
get { return _name; }
set
{
if (!string.IsNullOrWhiteSpace(value))
{
_name = value;
}
else
{
throw new ArgumentException("Name cannot be null or whitespace.");
}
}
}
// Public property for Age with a getter and setter
public int Age
{
get { return _age; }
set
{
if (value >= 0)
{
_age = value;
}
else
{
throw new ArgumentOutOfRangeException("Age cannot be negative.");
}
}
}
// Public method to display person details
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
}
Explanation
Private Fields: The fields _name and _age are private, meaning they cannot be accessed directly from outside the Person class. This encapsulates the data and restricts direct access.
Public Properties: The Name and Age properties provide a public interface to access and modify the private fields. The getters and setters allow controlled access and modification.
The setters include validation logic to ensure that invalid data is not assigned to the fields. For example, Name cannot be null or whitespace, and Age cannot be negative.
Public Method: The DisplayInfo method is a public method that provides a way to display the encapsulated data
Usage
class Program
{
static void Main()
{
// Create a new instance of the Person class
Person person = new Person();
// Set the properties
person.Name = "John Doe";
person.Age = 30;
// Display the person details
person.DisplayInfo(); // Output: Name: John Doe, Age: 30
// Try setting an invalid age
try
{
person.Age = -5; // This will throw an exception
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine(ex.Message); // Output: Age cannot be negative.
}
// Try setting an invalid name
try
{
person.Name = ""; // This will throw an exception
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message); // Output: Name cannot be null or whitespace.
}
}
}
Key Benefits of Encapsulation
Data Hiding: The internal state of the Person object is hidden from outside interference and misuse.
Controlled Access: The public properties provide controlled access to the private fields, allowing validation and other logic to be applied.
Modularity: Encapsulation helps in making the class more modular. Changes to the internal implementation can be made without affecting external code that uses the class.
Maintainability: The encapsulated code is easier to maintain and understand since the internal workings are hidden, and only the necessary parts are exposed.
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects," which can contain data in the form of fields (often known as attributes or properties) and code in the form of procedures (often known as methods). C# is a fully object-oriented language, which means it supports the principles of OOP:
Classes and Objects in C#
Classes and objects are fundamental concepts in Object-Oriented Programming (OOP). In C#, a class is a blueprint for creating objects. It defines a type by bundling data and methods that work on the data into one single unit. An object, on the other hand, is an instance of a class.
Class
A class is a user-defined blueprint or prototype from which objects are created. It represents a group of similar objects. A class can contain fields, methods, properties, constructors, and other class members.
Defining a Class
public class Person { // Fields private string name; private int age; // Constructor public Person(string name, int age) { this.name = name; this.age = age; } // Properties public string Name { get { return name; } set { name = value; } } public int Age { get { return age; } set { if (value >= 0) { age = value; } } } // Method public void DisplayInfo() { Console.WriteLine($"Name: {Name}, Age: {Age}"); } }
Object
An object is an instance of a class. When a class is defined, no memory is allocated until an object of that class is created. Objects can access the fields and methods defined in their class.
Creating an Object
public class Program { public static void Main(string[] args) { // Creating objects of the Person class Person person1 = new Person("Alice", 30); Person person2 = new Person("Bob", 25); // Accessing properties and methods person1.DisplayInfo(); // Output: Name: Alice, Age: 30 person2.DisplayInfo(); // Output: Name: Bob, Age: 25 // Modifying properties person1.Age = 31; person1.DisplayInfo(); // Output: Name: Alice, Age: 31 } }
Components of a Class
Fields: Variables that hold data for the class.
private string name;
private int age;
Properties: Provide a way to read, write, or compute the values of private fields. They are public by default.
public string Name { get { return name; } set { name = value; } } public int Age { get { return age; } set { if (value >= 0) { age = value; } } }
Methods: Functions that perform actions. They define the behavior of the class.
public void DisplayInfo() { Console.WriteLine($"Name: {Name}, Age: {Age}"); }
public void DisplayInfo() { Console.WriteLine($"Name: {Name}, Age: {Age}"); }
Constructors: Special methods that are called when an object is instantiated. They initialize the fields of the class.
public Person(string name, int age) { this.name = name; this.age = age; }
Access Modifiers
Access modifiers define the accessibility of the class members. The most common access modifiers in C# are:
Summary
Encapsulation is the bundling of data and methods that operate on the data into a single unit or class, and restricting access to some of the object's components.
Key Concepts:
Example: Encapsulation with a Person Class
Let's create a Person class that encapsulates the properties Name and Age.
public class Person { // Private fields private string _name; private int _age; // Public property for Name with a getter and setter public string Name { get { return _name; } set { if (!string.IsNullOrWhiteSpace(value)) { _name = value; } else { throw new ArgumentException("Name cannot be null or whitespace."); } } } // Public property for Age with a getter and setter public int Age { get { return _age; } set { if (value >= 0) { _age = value; } else { throw new ArgumentOutOfRangeException("Age cannot be negative."); } } } // Public method to display person details public void DisplayInfo() { Console.WriteLine($"Name: {Name}, Age: {Age}"); } }
Explanation
Private Fields: The fields _name and _age are private, meaning they cannot be accessed directly from outside the Person class. This encapsulates the data and restricts direct access.
Public Properties: The Name and Age properties provide a public interface to access and modify the private fields. The getters and setters allow controlled access and modification.
The setters include validation logic to ensure that invalid data is not assigned to the fields. For example, Name cannot be null or whitespace, and Age cannot be negative.
Public Method: The DisplayInfo method is a public method that provides a way to display the encapsulated data
Usage
class Program { static void Main() { // Create a new instance of the Person class Person person = new Person(); // Set the properties person.Name = "John Doe"; person.Age = 30; // Display the person details person.DisplayInfo(); // Output: Name: John Doe, Age: 30 // Try setting an invalid age try { person.Age = -5; // This will throw an exception } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(ex.Message); // Output: Age cannot be negative. } // Try setting an invalid name try { person.Name = ""; // This will throw an exception } catch (ArgumentException ex) { Console.WriteLine(ex.Message); // Output: Name cannot be null or whitespace. } } }
Key Benefits of Encapsulation
Data Hiding: The internal state of the Person object is hidden from outside interference and misuse.
Controlled Access: The public properties provide controlled access to the private fields, allowing validation and other logic to be applied.
Modularity: Encapsulation helps in making the class more modular. Changes to the internal implementation can be made without affecting external code that uses the class.
Maintainability: The encapsulated code is easier to maintain and understand since the internal workings are hidden, and only the necessary parts are exposed.
C# is primarily used on the Windows . NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.
The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.
The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.
C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.
Copyrights © 2024 letsupdateskills All rights reserved