This part of blog include general quick tips for short hand c# coding. I’ll write more about specific and advance tips in further parts.
If else conditions
There are various ways we can short hand if else condition coding
//Example 1- if condition without curly braces
int age = 10;
if (age > 17)
Console.WriteLine("Adult");
else if (age > 12)
Console.WriteLine("Teenager");
else
Console.WriteLine("Child");
//Example 2- if condition in single line
int age = 10;
if (age > 17) Console.WriteLine("Adult");
else if (age > 12 ) Console.WriteLine("Teenager");
else Console.WriteLine("Child");
//Example 3 - complete if condition in absolute single line
int age = 10;
if (age > 17) Console.WriteLine("Adult"); else if (age > 12 ) Console.WriteLine("Teenager"); else Console.WriteLine("Child");
?: conditional operator
The conditional operator evaluates boolean expression that appears prior ? mark. It returns value (expression) given between ? and : marks if evaluated true or value after : mark if evaluated false.
//? : conditional operator
int age = 18;
string AgeOfMajority = age > 17 ? "Adult" : "Teenager";
Console.WriteLine(AgeOfMajority);
It compacts the if else condition from 3 or more lines to just one line.
?. and ? Null Propagating Operators C# 6
New to .net framework, it’s not an everyday operator that comes into use but if practiced enough, it is very handy when delve into 2-3 or more level of chained access.
I picked this example from MSDN, you may want to look into it https://msdn.microsoft.com/en-us/library/dn986595.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
Definition as given on MSDN: Null Propagating operator test for null before performing a member access (?.) or index (?[) operation. These operators help you write less code to handle null checks, especially for descending into data structures.
// Length of customers if object is not null
int? length = customers?.Length;
// get first element if customers array not null
Customer first = customers?[0];
// getting count of orders if customers array is not null and first customer’s order is not null
int? count = customers?[0]?.Orders?.Count();
The last example demonstrates that null propagating operators are short-circuiting. If one operation in a chain of member access and index operation returns null, then the rest of the chain’s execution stops. Other operations with lower precedence in the expression continue.
+= Operator
This one of the handy operator avoids writing the variable name twice in case of adding for integer and appending for string types.
For example
//+= operator for string
string str = "Hello ";
str += "World";
Console.WriteLine(str);
//+= operator for integers
int cost = 50;
cost += 7;
Console.WriteLine(cost);
-= Operator
-= can only be applied to numeric types and give compile time error when used with string types
//+= operator for integers
int cost = 50;
cost -= 7;
Console.WriteLine(cost);
Similarly there are other arithmetic operators which are very handy. Read more at MSDN here https://msdn.microsoft.com/en-us/library/sa7629ew.aspx
Checking for bool condition
It may not even be worth mentioning but for some beginners and people not much familiar with nullable types it may be handy.
// using simple boolean check without using == operator
bool flightArrived = true;
if (flightArrived)
Console.WriteLine("Dad home");
else
Console.WriteLine("Waiting ......");
//For checking false condition use ! like
if (!flightArrived)
Console.WriteLine("waiting.....");
else
Console.WriteLine("Dad is coming");
Nullable Boolean types
When using nullable boolean types, the above code will not compile. Nullable bool can contain True, False or Null. That’s the reason why above code will fail.
Hence to check, it has to accompany with .hasValue test with a conversion
// nullable boolean check
bool? flightArrived = null;
if (flightArrived.HasValue && (bool)flightArrived)
Console.WriteLine("Dad home");
else
Console.WriteLine("Waiting ......");
Null-Coalesce operator (??)
Null coalesce operator test and assign objects value if not null otherwise use alternative value given after ?? (double question mark)
bool? userLogged = null;
// Null test – if userLogged is null then assign false otherwise assign whatever it contains
bool test = userLogged ?? false;
Console.WriteLine(test.ToString());
TryParse
Try parse is sort of extended version of Parse, available to all value types. The benefit about it is that it doesn’t throw the null exception if string value doesn’t contain the right value. It is safe and short to validate and extract value from string object.
– Int32.TryParse
– Float.TryParse
– bool.TryParse
String Operations
String IsnullOrEmpty
A single method to check for Null and Empty string, very handy to keep it short.
string IsNullOrWhiteSpace
Checks for null and whitespace, return true or false based on test.
String.Join operation
string[] Users = new string[] { "John", "Mike", "Jag", "Harry", "Lila" };
string str = string.Join(",", Users);
Console.WriteLine(str);
Property creation
The one line code for creating a property for e.g.
public string FirstName { get; set; }
public string LastName { get; set; }
Framework internally creates the private variable, getter and setter for it.
Want to create the readonly property try this
public string FirstName { get;}
Class Initialization
Initialize and assigning the reference of a class to method or property.
Suppose I have a class called Hollywood actors
public class HollywoodActor
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
//If I want to create the object and initialize its property, the normal code would be
HollywoodActor hollywoodActor = new HollywoodActor();
hollywoodActor.FirstName = "Arnold";
hollywoodActor.LastName = "Schwarzenegge";
//I can make it shorter by creating an overloaded constructor like
public HollywoodActor(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
// and then create object and assign property from constructor
HollywoodActor hollywoodActor = new HollywoodActor("Arnold", "Schwarzenegge");
//The other quick short hand that I use is without overload constructor
public class HollywoodActor
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
// Creating object of Hollywood actor class and assigning values
HollywoodActor hollywoodActor = new HollywoodActor()
{
FirstName = "Arnold",
LastName = "Schwarzenegge”;
};
//Example 2 - Creating list of Hollywood actors class and assign values
List actors = new List()
{
new HollywoodActor() { FirstName = "Tom", LastName = "Cruise" },
new HollywoodActor(){ FirstName = "Bruce", LastName = "Willis" },
new HollywoodActor(){ FirstName = "John", LastName = "Travolta" },
};
Event declaration and implementation
There are times when few code lines are written and a piece of work done within an event is written far from its logical grouping. It makes it readable it have it included at same location.
Shorthand can be achieved using lamda expression, for e.g. the simplest way of showing is to bind event at Form load event and write code as
btnTest.Click += (ss, ee) =>
MessageBox.Show("Inline event implementation");
};