I have the following method which encrypts a english text, given the plain text and the desired key:
/// <summary>
/// Encrypts english plain text using user defined key. Range for the key is from -25 to 25.
/// </summary>
/// <param name="plainText"></param>
/// <param name="keyValue"></param>
/// <returns></returns>
public static string encryptTextEng(String plainText,int keyValue)
{
string encText = "";
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
for (int i = 0; i < plainText.Length; i++)
{
if (plainText[i].ToString() == " ")
{
encText += " ";
}
for (int j = 0; j < alphabet.Length; j++)
{
if (String.Equals(alphabet[j].ToString(), plainText[i].ToString(), StringComparison.OrdinalIgnoreCase))
{
try
{
encText += alphabet[j + keyValue];
}
catch (Exception ex)
{
if (j + keyValue > 26)
{
encText += alphabet[j + keyValue - 26];
}
else if (j + keyValue < 0)
{
encText += alphabet[j + keyValue + 26];
}
}
}
}
}
return encText;
}
What are good programming practices I am missing here? Also I am not sure about the try/catch part I guess there are better ways to do it? Would it be a good idea to add a switch case which checks if the char it is currently reading is a punctuation character?
for-if
or aforeach-if
, I assume there's a missingWhere
. When I see nestedfor
s, I assume there's a missingSelectMany
. \$\endgroup\$