.NET API Documentation
Introduction to .NET APIs
The .NET platform provides a comprehensive set of APIs (Application Programming Interfaces) that allow developers to build a wide range of applications, from web services and desktop applications to mobile apps and games. These APIs are organized into namespaces, offering functionalities for everything from basic data manipulation to complex network communication.
This documentation provides an overview of key .NET namespaces and concepts, along with examples to help you understand and utilize these powerful tools effectively.
Core Namespaces
Understanding the core namespaces is fundamental to .NET development. They form the backbone of many common programming tasks.
System Namespace
The System namespace is the most fundamental namespace in .NET. It contains the base types and attributes used by all .NET applications, including fundamental types like Object, String, Int32, and exceptions.
Key Classes
Object: The ultimate base class of all types in .NET.String: Represents text.Int32: Represents a 32-bit signed integer.Exception: The base class for all exceptions.
Example: Working with Basic Types
using System;
public class Example
{
public static void Main(string[] args)
{
string message = "Hello, .NET!";
int number = 42;
Console.WriteLine(message);
Console.WriteLine($"The answer is: {number}");
}
}
System.Collections Namespace
This namespace provides interfaces and classes that define various collections of objects, such as lists, dictionaries, and queues. It includes both generic and non-generic collection types.
Key Classes
ArrayList: A non-generic collection of objects that can be individually accessed by an index.List<T>: A generic collection of objects that can be individually accessed by index.Dictionary<TKey, TValue>: A generic collection of key/value pairs.
Example: Using a Generic List
using System;
using System.Collections.Generic;
public class ListExample
{
public static void Main(string[] args)
{
List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");
names.Add("Charlie");
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
System.IO Namespace
Provides types that allow reading and writing to files and data streams, and types that represent and manage file system objects.
Key Classes
File: Provides static methods for creating, copying, deleting, moving, and opening files.Directory: Provides static methods for creating, moving, and enumerating through directories and subdirectories.StreamReader: Reads characters from a stream in a particular encoding.StreamWriter: Writes characters to a stream in a particular encoding.
Example: Reading from a File
using System;
using System.IO;
public class FileReader
{
public static void Main(string[] args)
{
try
{
using (StreamReader sr = new StreamReader("example.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (FileNotFoundException)
{
Console.WriteLine("Error: example.txt not found.");
}
}
}
System.Net Namespace
Provides a flexible, extensible model for network communication. It includes classes for network protocols, IP addresses, sockets, and web requests.
Key Classes
HttpClient: Sends HTTP requests and receives HTTP responses from a resource identified by a URI.IPAddress: Represents an Internet Protocol (IP) address.Socket: Provides a low-level network interface.
Example: Making an HTTP GET Request
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class HttpExample
{
public static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.GetAsync("https://api.example.com/data");
response.EnsureSuccessStatusCode(); // Throws an exception if the status code is not a success code.
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
}
}
}
}
System.Threading Namespace
Provides types that enable you to use multithreading for high-performance, scalable applications and all the components that are necessary to work with threads.
Key Classes
Thread: Represents an operating system thread.Task: Represents an asynchronous operation.CancellationToken: Propagates a notification that operations should be canceled.
Example: Using a Task for Background Work
using System;
using System.Threading;
using System.Threading.Tasks;
public class ThreadingExample
{
public static void Main(string[] args)
{
Console.WriteLine("Starting background task...");
Task backgroundTask = Task.Run(() =>
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"Background: {i}");
Thread.Sleep(500); // Simulate work
}
});
// Do other work on the main thread
for (int i = 0; i < 3; i++)
{
Console.WriteLine($"Main: {i}");
Thread.Sleep(300);
}
backgroundTask.Wait(); // Wait for the background task to complete
Console.WriteLine("Background task finished.");
}
}
Advanced Topics
Beyond the core namespaces, .NET offers advanced features for building robust and modern applications.
Asynchronous Programming
Asynchronous programming allows you to run operations that might take a long time (like I/O operations) in the background without blocking the main thread. This is crucial for responsive UI applications and scalable server applications. The primary keywords are async and await.
Example: Async Method
using System;
using System.Threading.Tasks;
public class AsyncDemo
{
public static async Task PerformLongOperationAsync()
{
Console.WriteLine("Starting long operation...");
await Task.Delay(2000); // Simulate a 2-second operation
Console.WriteLine("Long operation completed.");
}
public static async Task Main(string[] args)
{
Console.WriteLine("Before async call.");
await PerformLongOperationAsync();
Console.WriteLine("After async call.");
}
}
Reflection
Reflection allows you to inspect the metadata of assemblies, modules, and types at runtime. You can examine type information, discover members (methods, properties, fields), and invoke them.
Example: Inspecting a Type
using System;
using System.Reflection;
public class ReflectionDemo
{
public static void Main(string[] args)
{
Type stringType = typeof(string);
Console.WriteLine($"Type Name: {stringType.FullName}");
MethodInfo[] methods = stringType.GetMethods();
Console.WriteLine("Methods:");
foreach (var method in methods)
{
Console.WriteLine($"- {method.Name}");
}
}
}
Dependency Injection
Dependency Injection (DI) is a design pattern used to implement inversion of control (IoC) and achieve loose coupling between objects. .NET has built-in support for DI, making it easier to manage dependencies and write testable code.
Example: Basic DI Setup (Conceptual)
While a full DI setup involves more code (like using IServiceCollection and ServiceProvider), this illustrates the core concept.
// Assume ILogger and MyService interfaces and implementations exist
// class MyClass {
// private readonly ILogger _logger;
// public MyClass(ILogger logger) { // Constructor injection
// _logger = logger;
// }
// public void DoSomething() {
// _logger.Log("Doing something.");
// }
// }
// // In startup/configuration:
// // var services = new ServiceCollection();
// // services.AddTransient<ILogger, ConsoleLogger>();
// // services.AddTransient<MyClass>();
// // var serviceProvider = services.BuildServiceProvider();
// // // When needed:
// // var myObject = serviceProvider.GetService<MyClass>();
// // myObject.DoSomething();
API Design Guidelines
When designing your own APIs or contributing to .NET libraries, adhering to established guidelines ensures consistency, usability, and maintainability. Key principles include:
- Clarity and Simplicity: APIs should be easy to understand and use.
- Consistency: Naming conventions and patterns should be consistent across the API.
- Extensibility: Design APIs to allow for future growth and extension.
- Error Handling: Provide clear and informative error messages through exceptions.
- Performance: Be mindful of performance implications, especially for frequently called methods.
Refer to the official Microsoft API Design guidelines for detailed information.