C# Advanced Improvement
I. Methods 📝
In C#, methods are code blocks that perform specific tasks and can be called from other parts of the program. Methods facilitate code reuse, readability, and modularity.
1. Method Declaration 📝
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
}
Basic components:
- Access modifiers (such as
public,private) - Return type (like
void,int,string, etc.) - Method name (using camelCase)
- Parameter list (optional)
2. Method Invocation 🔗
Instance Method Call
Calculator calculator = new Calculator();
int result = calculator.Add(1, 2);
Console.WriteLine(result);
Static Method Call
public class MathHelper
{
public static int Square(int x)
{
return x * x;
}
}
// Call directly using the class name
int result = MathHelper.Square(4); // result = 16
3. Method Overloading 🔄
- Method names must be identical
- Parameter lists must be different: different number of parameters, different parameter types, or different parameter order
public class Calculator
{
// Add two integers
public int Add(int a, int b)
{
return a + b;
}
// Add two double-precision floating-point numbers
public double Add(double a, double b)
{
return a + b;
}
// Add three integers
public int Add(int a, int b, int c)
{
return a + b + c;
}
// Different parameter order
public int Add(int a, string b)
{
return a + int.Parse(b);
}
}
4. Method Parameters 📌
Required Parameters
public class MathOperations
{
public int Multiply(int x, int y)
{
return x * y;
}
}
Optional Parameters
Optional parameters provide a concise way to handle method calls with default behavior and must come after required parameters.
public class Printer
{
// Optional parameter with a default value
public void PrintMessage(string message, bool uppercase = false)
{
if (uppercase)
{
Console.WriteLine(message.ToUpper());
}
else
{
Console.WriteLine(message);
}
}
}
Value Parameters (Default)
void ModifyValue(int x)
{
x = 10; // Will not change the original value
}
Reference Parameters (ref)
void ModifyReference(ref int x)
{
x = 10; // Will change the original value
}
int number = 5;
ModifyReference(ref number); // number is now 10
Output Parameters (out)
Provides a concise mechanism for multiple return values, especially suitable for scenarios requiring both status and result returns.
public class UserValidator
{
// Validate user information
public bool ValidateUser(string input, out int userId, out string errorMessage)
{
userId = -1;
errorMessage = "";
// Parse user ID
if (!int.TryParse(input, out userId))
{
errorMessage = "Invalid user ID format";
return false;
}
// Check ID range
if (userId <= 0)
{
errorMessage = "User ID must be greater than 0";
return false;
}
return true;
}
}
public void ProcessUser()
{
UserValidator validator = new UserValidator();
// Call the method
bool isValid = validator.ValidateUser("123", out int userId, out string message);
if (isValid)
{
Console.WriteLine($"User ID: {userId}");
}
else
{
Console.WriteLine($"Validation failed: {message}");
}
}
Parameter Arrays (params)
public int Sum(params int[] numbers)
{
int total = 0;
foreach(int num in numbers)
total += num;
return total;
}
5. Return Types 📤
Methods with Return Values
public class Circle
{
public double CalculateArea(double radius)
{
return Math.PI * radius * radius;
}
}
Void Methods
public class Logger
{
public void LogError(string errorMessage)
{
Console.WriteLine($"Error: {errorMessage}");
}
}
II. Object-Oriented Programming 📦
1. Principles 📝
Object-oriented programming is based on four main principles: Encapsulation, Inheritance, Polymorphism, and Abstraction.
- Encapsulation allows bundling data and methods into a single unit (class) and restricting access to certain components.
- Inheritance allows one class (child or derived class) to inherit properties and methods from another class (parent or base class). This promotes code reuse and establishes hierarchical relationships between classes.
- Polymorphism is the ability of a single function or method to work in various ways based on its input or the object calling it. In
C#, polymorphism can be implemented through method overriding (using theoverridekeyword) and method hiding (using thenewkeyword to hide methods from the base class). - Abstraction allows developers to hide complex implementations and show only essential features of objects. This means users interact only with necessary content while internal workings remain hidden. In
C#, abstract classes and interfaces are tools that help implement abstraction.
These principles help design robust and scalable applications that are easy to maintain and further develop.
Encapsulation and Abstraction
These concepts help manage access to object data and implement high-level abstractions in programming:
- Encapsulation protects the internal state of objects and prevents unauthorized external access, allowing strict control over data and ensuring data integrity.
- Abstraction allows separation of implementation from interface and supports creating systems with higher flexibility and extensibility, enabling developers to reduce programming complexity and improve efficiency.
In C#, encapsulation is ensured through access modifiers such as private, protected, and public.
These modifiers determine the visibility of class members, allowing implementation details to be hidden and exposing only necessary APIs.
public: Full accessprivate: Access only within the classprotected: Access within class and derived classesinternal: Access within the same assembly
| Modifier | Same Class | Derived Class Same Assembly | Non-derived Class Same Assembly | Derived Class Different Assembly | Non-derived Class Different Assembly |
|---|---|---|---|---|---|
| public | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
| private | ✔️ | ❌ | ❌ | ❌ | ❌ |
| protected | ✔️ | ✔️ | ❌ | ✔️ | ❌ |
| internal | ✔️ | ✔️ | ✔️ | ❌ | ❌ |
| protected internal | ✔️ | ✔️ | ✔️ | ✔️ | ❌ |
| private protected | ✔️ | ✔️ | ❌ | ❌ | ❌ |
Inheritance and Polymorphism
Inheritance and polymorphism are key principles of object-oriented programming that ensure code reusability and flexibility:
- Inheritance allows creating a new class that inherits properties and methods from an existing class, improving code reusability and establishing hierarchical relationships between classes.
- Polymorphism is implemented through the ability to override methods in child classes using the
virtualandoverridekeywords, and through interfaces that allow different classes to have a consistent set of methods.
2. Classes and Objects 📝
Classes and objects are fundamental concepts in C# object-oriented programming. A class is a user-defined data type that encapsulates data and methods that operate on that data. An object is a specific instance of a class, representing an implementation of the defined class.
Class Basics
The default access modifier is internal, and the default access modifier for members is private.
public class Character
{
// Properties
public string Name { get; set; }
public int Level { get; set; }
public int Health { get; set; }
// Constructor
public Character(string name)
{
Name = name;
Level = 1;
Health = 100;
}
// Method
public void LevelUp()
{
Level++;
Health += 10;
Console.WriteLine($"{Name} leveled up to level {Level}");
}
// Virtual method, can be overridden by subclasses
public virtual void Introduction()
{
Console.WriteLine($"I am {Name}, currently at level {Level}");
}
}
Properties
In C#, properties are special members used to encapsulate fields in a class and provide access to them. Properties allow external code to access class internal data like fields, but with added security and maintainability through property accessors.
Properties typically consist of two accessors:
get: Used to retrieve the property valueset: Used to set the property value
public class Program
{
public static void Main()
{
// Create an instance of the Person class
Person person = new Person();
// Use the set accessor to set the Name property
person.Name = "Jack";
// Use the get accessor to retrieve the Name property and output it
Console.WriteLine("Person's name is: " + person.Name);
}
}
public class Person
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}