C#
C# is a versatile and powerful programming language developed by Microsoft as part of the .NET platform. It’s widely used for building a variety of applications, including web, desktop, mobile, and gaming applications.
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
Disadvantages of C#
Constructor:
In C#, a constructor is a special method that is automatically called when an instance of a class is created. Constructors are used to initialize objects and set default values for the fields of the class.
public class Car
{
public string model;
// Constructor
public Car()
{
model = "Mustang";
}
static void Main(string[] args)
{
Car myCar = new Car();
Console.WriteLine(myCar.model); // Outputs: Mustang
}
}
Types of Constructors
Parameterized Constructor:
Constructors can also take parameters to initialize fields with specific values.
public class Car
{
public string model;
// Parameterized Constructor
public Car(string modelName)
{
model = modelName;
}
static void Main(string[] args)
{
Car myCar = new Car("Tesla");
Console.WriteLine(myCar.model); // Outputs: Tesla
}
}
public class Example
{
// Private constructor
private Example()
{
Console.WriteLine("Private Constructor");
}
// Static method to demonstrate usage
public static void DisplayMessage()
{
Console.WriteLine("Hello from a static method!");
}
}
class Program
{
static void Main(string[] args)
{
// Example obj = new Example(); // This will cause a compile-time error
Example.DisplayMessage(); // Outputs: Hello from a static method!
}
}
Access modifiers:
The?protected internal?access modifier in C# is a combination of?protected?and?internal. It allows access to class members within the same assembly and also to derived classes, even if they are in different assemblies.
// Assembly1.cs
public class BaseClass
{
protected internal int myValue = 0;
}
public class TestAccess
{
void Access()
{
var baseObject = new BaseClass();
baseObject.myValue = 5; // Accessible because it's in the same assembly
}
}
// Assembly2.cs
public class DerivedClass : BaseClass
{
void Access()
{
var derivedObject = new DerivedClass();
derivedObject.myValue = 10; // Accessible because it's a derived class
}
}
Abstract Class:
An abstract class in C# is a class that cannot be instantiated directly. It is intended to be a base class from which other classes derive. Abstract classes can contain abstract methods, which are methods without a body that must be implemented by derived classes, as well as non-abstract methods with implementations.
Key Features of Abstract Classes
public abstract class Animal
{
// Abstract method (does not have a body)
public abstract void MakeSound();
// Non-abstract method
public void Sleep()
{
Console.WriteLine("Sleeping...");
}
}
public class Dog : Animal
{
// Implementing the abstract method
public override void MakeSound()
{
Console.WriteLine("Bark");
}
}
class Program
{
static void Main()
{
Dog myDog = new Dog();
myDog.MakeSound(); // Output: Bark
myDog.Sleep(); // Output: Sleeping...
}
}
Abstract classes are useful when you want to provide a common base class with some shared functionality, while forcing derived classes to implement specific behaviors.
Delegate:
A delegate in C# is a type that represents references to methods with a specific parameter list and return type. Delegates are similar to function pointers in C/C++, but they are object-oriented, type-safe, and secure
Key Features of Delegates
1.????? Type-Safe: Delegates ensure that the method signature matches the delegate signature.
2.????? Object-Oriented: Delegates are objects and can be passed as parameters, assigned to properties, and stored in collections.
3.????? Multicast: Delegates can hold references to multiple methods, allowing you to call multiple methods with a single delegate invocation.
领英推荐
// Declare a delegate
public delegate void DisplayMessage(string message);
public class Program
{
// Method that matches the delegate signature
public static void ShowMessage(string message)
{
Console.WriteLine(message);
}
static void Main()
{
// Instantiate the delegate
DisplayMessage messageDelegate = ShowMessage;
// Call the delegate
messageDelegate("Hello, World!"); // Output: Hello, World!
}
}
Multicast Delegates:
Delegates can also be multicast, meaning they can point to more than one method. When you invoke a multicast delegate, all the methods it points to are called in sequence.
public delegate void Notify();
public class Program
{
public static void Method1()
{
Console.WriteLine("Method1 called");
}
public static void Method2()
{
Console.WriteLine("Method2 called");
}
static void Main()
{
Notify notifyDelegate = Method1;
notifyDelegate += Method2;
notifyDelegate(); // Output: Method1 called
// Method2 called
}
}
Common Uses
·?????? Event Handling: Delegates are commonly used to define event handlers.
·?????? Callback Methods: Delegates can be used to pass methods as arguments to other methods, enabling callback functionality.
Array List:
In C#, an Array List is a non-generic collection that can dynamically resize itself to accommodate new elements. It is part of the System.Collections namespace and can hold elements of any data type
Key Features of?Array List
using System.Collections;
ArrayList myList = new ArrayList();
myList.Add(1);
myList.Add("Hello");
myList.Add(true);
int firstElement = (int)myList;
string secondElement = (string)myList;
foreach (var item in myList)
{
Console.WriteLine(item);
}
// Using object initializer
ArrayList anotherList = new ArrayList() { 2, "World", false };
While ArrayList is flexible, it is generally recommended to use the generic List<T> class for better type safety and performance.
Generics:
Generics in C# allow you to define classes, methods, interfaces, and delegates with a placeholder for the type of data they store or use. This makes your code more reusable, type-safe, and efficient by allowing you to work with any data type without sacrificing performance or type safety.
// Define a generic class
public class GenericList<T>
{
private List<T> items = new List<T>();
public void Add(T item)
{
items.Add(item);
}
public T Get(int index)
{
return items[index];
}
}
// Usage
class Program
{
static void Main()
{
// Create a list of integers
GenericList<int> intList = new GenericList<int>();
intList.Add(1);
intList.Add(2);
Console.WriteLine(intList.Get(0)); // Output: 1
// Create a list of strings
GenericList<string> stringList = new GenericList<string>();
stringList.Add("Hello");
stringList.Add("World");
Console.WriteLine(stringList.Get(1)); // Output: World
}
}
Generics are also commonly used with collections in the System.Collections.Generic namespace, such as List<T>, Dictionary<TKey, TValue>, and Queue<T>
Extension Methods:
Extension methods in C# allow you to add new methods to existing types without modifying their source code or creating a new derived type. This feature was introduced in C# 3.0 and is particularly useful for enhancing the functionality of classes you don’t have control over, such as those in the .NET Framework or third-party libraries.
How to Create an Extension Method
To create an extension method, you need to define a static method in a static class. The first parameter of the method specifies the type it extends and is preceded by the?this?keyword.
public static class StringExtensions
{
public static bool IsPalindrome(this string str)
{
int min = 0;
int max = str.Length - 1;
while (min < max)
{
if (str[min] != str[max]) return false;
min++;
max--;
}
return true;
}
}
// Usage
class Program
{
static void Main()
{
string example = "madam";
bool result = example.IsPalindrome();
Console.WriteLine(result); // Output: True
}
}
Static Class and Method: The extension method must be defined in a static class and must be a static method.
Keyword: The first parameter of the method specifies the type it extends and is preceded by the?this?keyword.
Instance Method Syntax: Even though the method is static, it is called as if it were an instance method on the extended type.
Extension methods are widely used in LINQ (Language Integrated Query) to extend IEnumerable<T> and other interfaces