Common Coding Problems in C Sharp
Contents
Common Coding Problems in C#
Magic Strings and Numbers
When there are hard coded strings in the code like filename to write (ie "log.txt"), check if they are used more than once. if it's more than once it's better to define it on top of the class like
static readonly string LOGNAME = "log.txt";
it's same with the numbers like buffer size.
static readonly int BUFFERSIZE = 250;
About if
wrapping if with curly braces can be ignored if it's one line afterwards. To overcome this problem
either
if (test) Console.WriteLine("it's true");
or
if (test)
{
Console.WriteLine("it's true");
}
String Concatenation
plus should not be used to concatenate strings like beolw
var s = "This" + " is" + " a" + " string";
instead
var s = string.Concat("This", " is", " a" , " string");
or
string.Format("This is {0} a value", v);
When it comes to multiline strings
var x = "this is a line"; x += "And some more line"; x += " and some more";
instead
StringBuilder bldr = new StringBuilder();
bldr.Append("This is a line");
bldr.AppendFormat("Foo Bar {0]", 1);
bldr.AppendLine("");
var result = bldr.ToString;
const vs readonly
const created when app started (actually design time) and readonly created when it's first used (run time). This causes a problem when const is in a library and used in an app. library may not be recompiled thus makes const value inconsistent.
Bad IDisposible usage
for disposible objects like FileStream
FileStream stream = new FileStream() // ..... stream.Close(); stream.Dispose();
instead
using(FileStream stream = new FileStream())
{
// ......
stream.Close();
Enumaration Initialization
enter first value as 0 in enum like
public enum Position
{
Invalid = 0,
Pitcher,
Catcher ,
....
}
public enum PitcherType
{
Unknown = 0,
Starting = 1,
LongRelief = 2,
....
}
Large method bodies
Normally a method should fit in a normal monitor (upto 60 lines) Name of the method can be seld descriptive. Thus you don't need to write inline comments