Top 16 C# Programming Tips & Tricks

Publicado el - Última modificación el

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

public Tuple < int, string, string > GetEmployee()

int employeeId = 1001;

string firstName = "Rudy";

string lastName = "Koertson";

//Create a tuple and return

return Tuple.Create(employeeId, firstName, lastName);
  1. Do not bother with Temporary Collections, Use Yield instead

A temporary list that holds salvaged and returned items may be created when developers want to pick items from a collection. When using a temporary list, use this C# code.

public List < int > GetValuesGreaterThan100(List < int > masterCollection)

List < int > tempResult = new List < int > ();

foreach(var value in masterCollection)

if (value > 100)

 temp result.Add(value);

return temp result;

In order to prevent the temporary collection from being used, developers can use yield. Yield gives out results according to the result set enumeration. When using yield, use this code

public IEnumerable<int> GetValuesGreaterThan100(List<int> masterCollection)

           foreach (var value in masterCollection)

               if (value > 100)

                   yield return value;

Developers also have the option of using LINQ.

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
  1. 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());
  1. 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.

class Program

       static void Main(string[] args)

           ExternalEntity entity = new ExternalEntity()

               Id = 1001,

               FirstName = "Dave",

               LastName = "Johnson"

           };

           MyEntity convertedEntity = (MyEntity)entity;

    class MyEntity

       public int Id { get; set; }

       public string FullName { get; set; }

        public static explicit operator MyEntity(ExternalEntity externalEntity)

                 return new MyEntity()

                           Id = externalEntity.Id,

               FullName = externalEntity.FirstName + " " + externalEntity.LastName

   class ExternalEntity

    public int Id { get; set; }

       public string FirstName { get; set; }

       public string LastName { get; set; }
  1. 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.

   

  public void RunDataOperation()

                 try

                  Intialize();

               ConnectDatabase();

               Execute ();

            catch (Exception exception)

              throw exception;

      Preserve the exact stack trace throw as seen below

       public void RunDataOperation()

                   try

                   Intialize();

               ConnectDatabase();

               Execute();

                       catch (Exception)

                           throw;
  1. Enum Flags Attribute

Using flags attribute to decorate the enum in C# enables it as bit fields. This enables developers to collect the enum values. One can use the following C# code.

   class Program

       static void Main(string[] args)

           int snakes = 14;

           Console.WriteLine((Reptile)snakes);

   [Flags]

   enum Reptile

       BlackMamba = 2,

       CottonMouth = 4,

       Wiper = 8,

       Crocodile = 16,

       Aligator = 32

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
  1. 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

  class Program

           static void Main(string[] args)

                   MyClass myClass = new MyClass();

           ((List<string>)myClass.ReadOnlyNameCollection).Add("######From Client#####");

            myClass.Print();

           class MyClass

           List<string> _nameCollection = new List<string>();

       public MyClass()

         _nameCollection.Add("Rob");

           _nameCollection.Add("John");

           _nameCollection.Add("Jummy");

           _nameCollection.Add("Derek");

       public IEnumerable<string> ReadOnlyNameCollection

       get { return _nameCollection.AsEnumerable(); }

       public void Print()

       foreach (var item in ReadOnlyNameCollection)

        Console.WriteLine(item);

This code modifies the list and gives it a new name. In order to avoid this, add AsReadOnly as opposed to AsEnumerable.

       public IEnumerable<string> ReadOnlyNameCollection

       get { return _nameCollection.AsReadOnly(); }
  1. Data Type Conversion

More often than not, developers have to alter data types for different reasons. For example, converting a set value decimal variable to an int or Integer, the explicit conversion is done as follows.

int j = 0;

decimal money = 9500.34m;

j = (int)money; // An explicit conversion using cast operator.

Using the Convert class which supports full Data Type conversion between all data types is the best option.

int money = 0;

string uservalue = null;

uservalue = Console.ReadLine();

money = Convert.ToInt32(uservalue);

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

SHA1 sha1 = SHA1.Create();

try

StringBuilder sb = new StringBuilder();

byte[] data = Encoding.UTF8.GetBytes(text);

byte[] hash = sha1.ComputeHash(data);

foreach (byte b in hash)

sb.Append(b.ToString("x2").ToLower());

hashed = sb.ToString();

finally

if (sha1 != null)

((IDisposable)sha1).Dispose();

Utilizing the using statement once is the best option as seen below:

// 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
  1. 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:

using Excel = Microsoft.Office.Interop.Excel;

var excelapp = new Excel.Application();

excelapp.Visible = true;
  1. Object Initializers

When using the outdated method of initializing property values from outside the class, developers have to initialize the properties separately or write using a constructor. See the following example

Child child = new Child();

child.Age = 10;

child.Name = "Bryan";

child.StreetAddress = "Seattle, WA 98124";

This code can be written as:

Child child = new Child() { Age = 10, Name = "Bryan", StreetAddress = "Seattle, WA 98124" };

This language attribute exists in C# 3.0 and current versions.

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;
  1. 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.

Publicado 10 agosto, 2017

LucyKarinsky

Software Developer

Lucy is the Development & Programming Correspondent for Freelancer.com. She is currently based in Sydney.

Siguiente artículo

JavaScript vs Java: The Facts