Skip to main content

Posts

Showing posts with the label C# Coding Best Practices

C# coding best practices with examples

 C# coding best practices and coding standards are guidelines and conventions that developers should follow to write maintainable, readable, and efficient code. Here are a few examples of C# coding best practices:     1) Use meaningful and consistent naming conventions. For example, use camelCase for local variables and PascalCase for class and method names.     2) Use the using statement for disposable objects, such as file streams and database connections, to ensure that they are properly disposed of.     3) Use the async and await keywords to make asynchronous calls and avoid blocking the UI thread.     4) Use exception handling to handle errors and unexpected conditions. Use specific exception types rather than the base Exception type.     5) Use the null-coalescing operator (??) to provide a default value when a nullable type is null.     6) Use StringBuilder instead of concatenating strings in a loop.     7) Use the ?. operator to check for null values before accessing an object&

What are memory leaks in C#, causes and preventive measures.

A memory leak in C# occurs when an application holds onto memory that is no longer needed. This can happen when an object is no longer being used but is still being referenced by the application, preventing the memory it occupies from being freed by the Garbage Collector (GC) from .net Framework.  Memory leaks can cause an application to slow down or crash, as the amount of available memory is gradually exhausted. They can be caused by various factors, such as improperly managing memory, not releasing resources, or creating circular references.  To avoid memory leaks, it is important to follow best practices for managing memory and properly disposing of resources when they are no longer needed. The following factors contributing to the memory leaks:   Unsubscribed event handlers: If an event handler is not unsubscribed when it's no longer needed, it will continue to hold a reference to the object it's associated with, preventing it from being collected by the garbage collector