Top 16 C# Programming Tips & Tricks

Programming can be described as the process which leads a computing problem from its original formulation, to an executable computer program. This process involves activities such as developing understanding, analysis, generating algorithms, verification of essentials of algorithms - including their accuracy and resources utilization - and coding of algorithms in the proposed programming language. The source code can be written in one or more programming languages. The purpose of programming is to find a series of instructions that can automate solving of specific problems, or performing a particular task. Programming needs competence in various subjects including formal logic, understanding the application, and specialized algorithms.

1. Write Unit Test for Non-Public Methods

Many developers do not write unit test methods for non-public assemblies. This is because they are invisible to the test project. C# enables one to enhance visibility between the assembly internals and other assemblies. The trick is to include //Make the internals visible to the test assembly [assembly: InternalsVisibleTo("MyTestAssembly")] in the AssemblyInfo.cs file.

2. Tuples

Many developers build a POCO class in order to return multiple values from a method. Tuples are initiated in .NET Framework 4.0. They can be used effectively as follows

4. Making a retirement announcement

Developers who own re-distributable components and probably want to detract a method in the near future, can embellish it with the outdated feature to connect it with the clients. Check out the following C# sample code

[Obsolete("This method will be deprecated soon. You could use XYZ alternatively.")]

public void MyComponentLegacyMethod()
//Here is the implementation

Upon compilation, a client gets a warning upon with the message. To fail a client build that is using the detracted method, pass the additional Boolean parameter as True.

[Obsolete("This method is deprecated. You could use XYZ alternatively.", true)]

public void MyComponentLegacyMethod()
//Here is the implementation

Deferred Execution While Writing LINQ Queries

When a LINQ query is written in .NET, it can only perform the query when the LINQ result is approached. The occurrence of LINQ is known as deferred execution. Developers should understand that in every result set approach, the query gets executed over and over. In order to prevent a repetition of the execution, change the LINQ result to List after execution. Below is an example

public void MyComponentLegacyMethod(List<int> masterCollection)

//Without the ToList this linq query will be executed twice because of the following usage
var result = masterCollection.Where(i => i > 100).ToList();
Console.WriteLine(result.Count());
Console.WriteLine(result.Average());

Explicit keyword conversions for business entities

Utilize the explicit keyword to describe the alteration of one business entity to another. The alteration method is conjured once the alteration is applied in code. Below is an example.

Absorbing the Exact Stack Trace

In the catch block of a C# program, if an exception is thrown as shown below and probably a fault has occurred in the method ConnectDatabase, the thrown exception stack trace only indicates the fault has happened in the method RunDataOperation. This means that the exact error source will have been lost as seen below.

The output for this code will be “BlackMamba, CottonMouth, Wiper”. When the flags attribute is removed, the output will remain 14.

9. Implementing the Base Type for a Generic Type

When developers want to enforce the generic type provided in a generic class such that it will be able to inherit from a particular interface, they can follow this sample

class MyGenricClass<T> where T : IMyInterface
//Body of the class come in here
You could also do it at the method level.
class MyGenricClass
public void MyGenericMethod<T>(T t) where T : IMyInterface
//Generic implementation goes in here

Using Property as IEnumerable doesn’t make it Read-only

When an IEnumerable property gets exposed in a created class, callers can modify as follows

In the former code-snippet, an explicit conversion is done using a cast operator. In the latter code-snippet, the Convert class is used while the ToInt32() method is invoked to convert a string into an int. Explicit conversions require a cast operator. In addition, the destination and source variables should be compatible. Conversion with the assistance of a helper class such as Convert enables us to convert between non-compatible types. This does not need the use of a cast operator.

12. Using Statement

Memory allocation is as paramount as freeing memory. In C# there is a Garbage Collector which plays an important role. However, various classes in the .NET library enforce the IDisposable interface which requires manual object disposal. The code-snippet below indicates the creation of the SHAI class and subsequently disposes the object

// Allocate
using (System.Security.Cryptography.SHA1 sha1
= System.Security.Cryptography.SHA1.Create())
//Use the sha1 to computer the hash.
//sha1 can only be used inside this code-block
//Automatically Disposed

Namespace Alias Qualifier

The Namespace Alias Qualifier in C# allows developers to utilize the alias name as opposed to the complete namespace. This is useful because namespaces can become very long. Check out the example below:

15. Nullable Types

C# developers know how to work with various value types such as so one, chat, double, bool, and int. While they are useful, all of them can't be set to null. For instance, a bool variable will only hold the values either false or true. Inserting the symbol ("?") makes it possible to assign null.

Nullable<bool> status = null;
int? i = null;

Establishing whether a String is Null?

A string.IsNullOrEmpty tests strings by looking for null or empty string references. The static method IsNullOrEmpty allows developers to test whether a string is empty or null. See below

if (string.IsNullOrEmpty(s))
return "This string is null or empty.";
else
return string.Format("This string is not null or empty, it equals to \"{0}\" ", s);

Conclusion

Developers can improve the performance of their applications by utilizing asynchronous programming. This also helps prevent congestion.

Do you have additional tips and tricks to share with us? Leave us a comment and remember to share this article widely.