Literals should not be duplicated

 In  Programming, Literals refer to fixed or constant values, that have been hard-coded directly into your application source code, which is readily understood by the compiler and turned into the correct representation at compile time, for an example: 

int x = 10; 

Here, 10 is an integer type constant/literal, which is assigned to the variable "x"

As we mentioned above, literals do not necessarily seem in local variable assignments. They can equally appear as parameters to a method also, for an example:

 Console.WriteLine("Hello"); 

Here, "Hello" is a string type constant/literal, which is used as a parameter of the WriteLine() method of the Console class.

The type of literal is defined by the value which is used as a literal in the application source code. In this article, literal is the main discussion point instead of their types.


Why literals should not be duplicated?

The duplicated literals make the process of refactoring error-prone since you must be sure to update all occurrences. Also, it will increase the application memory size due to multiple duplicate copies of the same literal.


Use Constant Literals

We can solve above mentions problems by using constant literal. As we know, constant literal value is not changeable throughout the application life cycle. The constants literal can be referenced from many places, but only need to be updated in a single place, for an example:

const int x = 10; 
Console.WriteLine(x);









Vikash Chauhan

C# & .NET experienced Software Engineer with a demonstrated history of working in the computer software industry.

Post a Comment

Previous Post Next Post

Contact Form