Showing posts with label Code Guidelines. Show all posts

C# codes that improve productivity - Part 2

My early post, I explained five c# shorthands code tips. Again, I have listed another 5 C# shorthands that you can use to make your code too short.

Read my previous post at C# codes that improve productivity - Part 1

6. Nullable objects

A variable needs to have a value, it cannot be null. Sometimes it would be handy it was possible to assign "null" (eg. undefined) to a variable.

.NET 2.0 introduced the Nullable generic that makes this possible. The following two lines produce exactly the same object:
Nullable x = null;
int? x = null;

By putting a ? following a variable definition the compiler will wrap a Nullable generic around the type.

7. Automatic Properties

C# 3.0 introduced automatic properties. A property typically consists of a private variable which is exposed to the outside world through getters and setters (get;set;).

The following is common example of this:
public class Person
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
}

From C# 3.0 on we can reduce the above code to:
public class Person
{
public string Firstname { get; set; }
}

The C# compiler will automatically generate a backing variable and the correct get and set properties. Why is this useful? After all you could have just made a string variable in the class public instead.

By defining it as a property allows you to add the actual validation logic to your class at a later stage. The in-memory signature of the class won’t change which means that any external libraries compiled against your code will not have to be recompiled.

8. Type inference

In typical C# you will always carefully spell out your definitions:
string MyString = "Hello World";

From the right side of the declaration it is obvious that only one type (string) will ever match this definition. So instead of us doing the work, why not let the compiler figure this out?
var MyString = "Hello World";

The above definition will also create a string variable named "MyString". It is important to note that C# is still strongly typed.There is no performance impact results from using type inference.

The compiler does all the work figuring out the data type at compile time. Of course this feature created two opposite camps, one that thinks var should be liberally applied, and another one that abhors the whole idea. The middle ground seems to be that var should be used there were its use is obvious.
var SeniorStaff = Employees.Where(s => s.Age > 35);
foreach(var Member in SeniorStaff)
Console.WriteLine("Name: {0} Age: {1}",Member.Name,Member.Age);

For example what type would SeniorStaff be ?
((System.Linq.Enumerable.Iterator<<>f__AnonymousType0>)(SeniorStaff))

9. Lambda Expressions

C# 2.0 introduced anonymous methods, which are methods defined inside a method. Incredibly powerful and a nice way to put all kinds of evaluation logic inside your code they had the drawback that they could be quite hard to read.
Func mySeniorStaffFilter = delegate(int a) { return a > 35; }; 

The above method takes an integer as a parameter, and returns a boolean. It checks if the staff member passed to it is older than 35. If so, it returns true.

Lamba expressions make things a little easier to read, while being functionally exactly the same:
Func mySeniorStaffFilter = a => a > 35; 

Even better, you can define them anywhere a delegate would have fitted:
var SeniorStaff = Employees.Where(s => s.Age > 35); 

10. string.IsNullOrEmpty

Not really a language feature, but a useful little library function in its own right. How often do you need to test if a string is empty? Or null? The string.IsNullOrEmpty method returns true if this is the case.
if (String.IsNullOrEmpty(s) == true)
return "is null or empty";
else
return String.Format("(\"{0}\") is not null or empty", s);

Thanks : dijksterhuis

Hope this will help you. A 'Thank You' would be nice!

C# codes that improve productivity - Part 2

My early post, I explained five c# shorthands code tips. Again, I have listed another 5 C# shorthands that you can use to make your code too short.

Read my previous post at C# codes that improve productivity - Part 1

6. Nullable objects

A variable needs to have a value, it cannot be null. Sometimes it would be handy it was possible to assign "null" (eg. undefined) to a variable.

.NET 2.0 introduced the Nullable generic that makes this possible. The following two lines produce exactly the same object:
Nullable x = null;
int? x = null;

By putting a ? following a variable definition the compiler will wrap a Nullable generic around the type.

7. Automatic Properties

C# 3.0 introduced automatic properties. A property typically consists of a private variable which is exposed to the outside world through getters and setters (get;set;).

The following is common example of this:
public class Person
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
}

From C# 3.0 on we can reduce the above code to:
public class Person
{
public string Firstname { get; set; }
}

The C# compiler will automatically generate a backing variable and the correct get and set properties. Why is this useful? After all you could have just made a string variable in the class public instead.

By defining it as a property allows you to add the actual validation logic to your class at a later stage. The in-memory signature of the class won’t change which means that any external libraries compiled against your code will not have to be recompiled.

8. Type inference

In typical C# you will always carefully spell out your definitions:
string MyString = "Hello World";

From the right side of the declaration it is obvious that only one type (string) will ever match this definition. So instead of us doing the work, why not let the compiler figure this out?
var MyString = "Hello World";

The above definition will also create a string variable named "MyString". It is important to note that C# is still strongly typed.There is no performance impact results from using type inference.

The compiler does all the work figuring out the data type at compile time. Of course this feature created two opposite camps, one that thinks var should be liberally applied, and another one that abhors the whole idea. The middle ground seems to be that var should be used there were its use is obvious.
var SeniorStaff = Employees.Where(s => s.Age > 35);
foreach(var Member in SeniorStaff)
Console.WriteLine("Name: {0} Age: {1}",Member.Name,Member.Age);

For example what type would SeniorStaff be ?
((System.Linq.Enumerable.Iterator<<>f__AnonymousType0>)(SeniorStaff))

9. Lambda Expressions

C# 2.0 introduced anonymous methods, which are methods defined inside a method. Incredibly powerful and a nice way to put all kinds of evaluation logic inside your code they had the drawback that they could be quite hard to read.
Func mySeniorStaffFilter = delegate(int a) { return a > 35; }; 

The above method takes an integer as a parameter, and returns a boolean. It checks if the staff member passed to it is older than 35. If so, it returns true.

Lamba expressions make things a little easier to read, while being functionally exactly the same:
Func mySeniorStaffFilter = a => a > 35; 

Even better, you can define them anywhere a delegate would have fitted:
var SeniorStaff = Employees.Where(s => s.Age > 35); 

10. string.IsNullOrEmpty

Not really a language feature, but a useful little library function in its own right. How often do you need to test if a string is empty? Or null? The string.IsNullOrEmpty method returns true if this is the case.
if (String.IsNullOrEmpty(s) == true)
return "is null or empty";
else
return String.Format("(\"{0}\") is not null or empty", s);

Thanks : dijksterhuis

Hope this will help you. A 'Thank You' would be nice!

C# codes that improve productivity - Part 2

My early post, I explained five c# shorthands code tips. Again, I have listed another 5 C# shorthands that you can use to make your code too short.

Read my previous post at C# codes that improve productivity - Part 1

6. Nullable objects

A variable needs to have a value, it cannot be null. Sometimes it would be handy it was possible to assign "null" (eg. undefined) to a variable.

.NET 2.0 introduced the Nullable generic that makes this possible. The following two lines produce exactly the same object:
Nullable x = null;
int? x = null;

By putting a ? following a variable definition the compiler will wrap a Nullable generic around the type.

7. Automatic Properties

C# 3.0 introduced automatic properties. A property typically consists of a private variable which is exposed to the outside world through getters and setters (get;set;).

The following is common example of this:
public class Person
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
}

From C# 3.0 on we can reduce the above code to:
public class Person
{
public string Firstname { get; set; }
}

The C# compiler will automatically generate a backing variable and the correct get and set properties. Why is this useful? After all you could have just made a string variable in the class public instead.

By defining it as a property allows you to add the actual validation logic to your class at a later stage. The in-memory signature of the class won’t change which means that any external libraries compiled against your code will not have to be recompiled.

8. Type inference

In typical C# you will always carefully spell out your definitions:
string MyString = "Hello World";

From the right side of the declaration it is obvious that only one type (string) will ever match this definition. So instead of us doing the work, why not let the compiler figure this out?
var MyString = "Hello World";

The above definition will also create a string variable named "MyString". It is important to note that C# is still strongly typed.There is no performance impact results from using type inference.

The compiler does all the work figuring out the data type at compile time. Of course this feature created two opposite camps, one that thinks var should be liberally applied, and another one that abhors the whole idea. The middle ground seems to be that var should be used there were its use is obvious.
var SeniorStaff = Employees.Where(s => s.Age > 35);
foreach(var Member in SeniorStaff)
Console.WriteLine("Name: {0} Age: {1}",Member.Name,Member.Age);

For example what type would SeniorStaff be ?
((System.Linq.Enumerable.Iterator<<>f__AnonymousType0>)(SeniorStaff))

9. Lambda Expressions

C# 2.0 introduced anonymous methods, which are methods defined inside a method. Incredibly powerful and a nice way to put all kinds of evaluation logic inside your code they had the drawback that they could be quite hard to read.
Func mySeniorStaffFilter = delegate(int a) { return a > 35; }; 

The above method takes an integer as a parameter, and returns a boolean. It checks if the staff member passed to it is older than 35. If so, it returns true.

Lamba expressions make things a little easier to read, while being functionally exactly the same:
Func mySeniorStaffFilter = a => a > 35; 

Even better, you can define them anywhere a delegate would have fitted:
var SeniorStaff = Employees.Where(s => s.Age > 35); 

10. string.IsNullOrEmpty

Not really a language feature, but a useful little library function in its own right. How often do you need to test if a string is empty? Or null? The string.IsNullOrEmpty method returns true if this is the case.
if (String.IsNullOrEmpty(s) == true)
return "is null or empty";
else
return String.Format("(\"{0}\") is not null or empty", s);

Thanks : dijksterhuis

Hope this will help you. A 'Thank You' would be nice!

C# codes that improve productivity - Part 1

Below I have listed 5 C# shorthands that you can use to make your code tighter and less wordy. No doubt you know one or more already — but do you currently use all five of them ?

1. The ? conditional operator

It allows you to compress a common if-then-else pattern into a single assignment.
int x = 10;
int y = 20;
int max;

if (x > y)
max = x;
else
max = y;

Using the (Question) ? Positive Answer : Negative Answer patterns the above can be rewritten as:
int x = 10;
int y = 20;
int max = (x > y) ? x : y;

2. Null-Coalesce operator (??)

How often do you test for null values in your code? Often? Then the null-coalesce operator (??) comes in handy.

To see how it works consider the following code example:
object cache = null;
object d = new object();
object e;

if (c != null)
e = c; // c is an object
else
e = d;

t is obvious that we can rewrite this using the single ? operator :
object cache = null;
object d = new object();
object e = (c != null) ? c : d;

3. Object Initializers

After you create a new object you often have to assign one or more of its properties. With the introduction of C# 3.0 it is now possible to use object initializers to both improve the readability of this, and to shorten your code.
Customer c = new Customer();
c.Name = "James";
c.Address = "204 Lime Street";

can be re-written as:
Customer c = new Customer { Name="James", Address = "204 Lime Street" };

4. The using statement

Often you will need to allocate a system resource such as a font, file handle, network resource etc. Each time you need such a resource there are three critical steps to go through: You acquire the resource, you use it, and then you dispose of it.

If you forget to properly dispose of it you will have created a memory or resource leak. This is best illustrated through the following patterns:
// 1. Allocation of the object
Font font1 = new Font("Arial", 10.0f);
try
{
// 2. The bit where we use the resource
}
finally
{
// 3. Disposal of the object
if (font1 != null)
((IDisposable)font1).Dispose();
}

The using statement allows us to compress this down to:
// Allocate the resource
using (Font font1 = new Font("Arial", 10.0f))
{
// The bit where we use the resource
}
// Disposal is automatic

The using statement is intended to be used with objects that implement the "IDisposable" interface which in practice is all .NET objects that allocate and manage resources.

5. Aliases for long winded namespaces and types

The names of C# identifiers can become quite long. If you are doing Microsoft Office automation in C# you might want to do something simple like open MS Word and change a document. You can use the "using" statement to create an alias for either a class or a namespace.
using Word = Microsoft.Office.Interop.Word;
...
Word.Application = new Word.Application() { Visible = True; }

Thanks : dijksterhuis

Read more tips at C# codes that improve productivity - Part 2

Hope this will help you. A 'Thank You' would be nice!

C# codes that improve productivity - Part 1

Below I have listed 5 C# shorthands that you can use to make your code tighter and less wordy. No doubt you know one or more already — but do you currently use all five of them ?

1. The ? conditional operator

It allows you to compress a common if-then-else pattern into a single assignment.
int x = 10;
int y = 20;
int max;

if (x > y)
max = x;
else
max = y;

Using the (Question) ? Positive Answer : Negative Answer patterns the above can be rewritten as:
int x = 10;
int y = 20;
int max = (x > y) ? x : y;

2. Null-Coalesce operator (??)

How often do you test for null values in your code? Often? Then the null-coalesce operator (??) comes in handy.

To see how it works consider the following code example:
object cache = null;
object d = new object();
object e;

if (c != null)
e = c; // c is an object
else
e = d;

t is obvious that we can rewrite this using the single ? operator :
object cache = null;
object d = new object();
object e = (c != null) ? c : d;

3. Object Initializers

After you create a new object you often have to assign one or more of its properties. With the introduction of C# 3.0 it is now possible to use object initializers to both improve the readability of this, and to shorten your code.
Customer c = new Customer();
c.Name = "James";
c.Address = "204 Lime Street";

can be re-written as:
Customer c = new Customer { Name="James", Address = "204 Lime Street" };

4. The using statement

Often you will need to allocate a system resource such as a font, file handle, network resource etc. Each time you need such a resource there are three critical steps to go through: You acquire the resource, you use it, and then you dispose of it.

If you forget to properly dispose of it you will have created a memory or resource leak. This is best illustrated through the following patterns:
// 1. Allocation of the object
Font font1 = new Font("Arial", 10.0f);
try
{
// 2. The bit where we use the resource
}
finally
{
// 3. Disposal of the object
if (font1 != null)
((IDisposable)font1).Dispose();
}

The using statement allows us to compress this down to:
// Allocate the resource
using (Font font1 = new Font("Arial", 10.0f))
{
// The bit where we use the resource
}
// Disposal is automatic

The using statement is intended to be used with objects that implement the "IDisposable" interface which in practice is all .NET objects that allocate and manage resources.

5. Aliases for long winded namespaces and types

The names of C# identifiers can become quite long. If you are doing Microsoft Office automation in C# you might want to do something simple like open MS Word and change a document. You can use the "using" statement to create an alias for either a class or a namespace.
using Word = Microsoft.Office.Interop.Word;
...
Word.Application = new Word.Application() { Visible = True; }

Thanks : dijksterhuis

Read more tips at C# codes that improve productivity - Part 2

Hope this will help you. A 'Thank You' would be nice!

C# codes that improve productivity - Part 1

Below I have listed 5 C# shorthands that you can use to make your code tighter and less wordy. No doubt you know one or more already — but do you currently use all five of them ?

1. The ? conditional operator

It allows you to compress a common if-then-else pattern into a single assignment.
int x = 10;
int y = 20;
int max;

if (x > y)
max = x;
else
max = y;

Using the (Question) ? Positive Answer : Negative Answer patterns the above can be rewritten as:
int x = 10;
int y = 20;
int max = (x > y) ? x : y;

2. Null-Coalesce operator (??)

How often do you test for null values in your code? Often? Then the null-coalesce operator (??) comes in handy.

To see how it works consider the following code example:
object cache = null;
object d = new object();
object e;

if (c != null)
e = c; // c is an object
else
e = d;

t is obvious that we can rewrite this using the single ? operator :
object cache = null;
object d = new object();
object e = (c != null) ? c : d;

3. Object Initializers

After you create a new object you often have to assign one or more of its properties. With the introduction of C# 3.0 it is now possible to use object initializers to both improve the readability of this, and to shorten your code.
Customer c = new Customer();
c.Name = "James";
c.Address = "204 Lime Street";

can be re-written as:
Customer c = new Customer { Name="James", Address = "204 Lime Street" };

4. The using statement

Often you will need to allocate a system resource such as a font, file handle, network resource etc. Each time you need such a resource there are three critical steps to go through: You acquire the resource, you use it, and then you dispose of it.

If you forget to properly dispose of it you will have created a memory or resource leak. This is best illustrated through the following patterns:
// 1. Allocation of the object
Font font1 = new Font("Arial", 10.0f);
try
{
// 2. The bit where we use the resource
}
finally
{
// 3. Disposal of the object
if (font1 != null)
((IDisposable)font1).Dispose();
}

The using statement allows us to compress this down to:
// Allocate the resource
using (Font font1 = new Font("Arial", 10.0f))
{
// The bit where we use the resource
}
// Disposal is automatic

The using statement is intended to be used with objects that implement the "IDisposable" interface which in practice is all .NET objects that allocate and manage resources.

5. Aliases for long winded namespaces and types

The names of C# identifiers can become quite long. If you are doing Microsoft Office automation in C# you might want to do something simple like open MS Word and change a document. You can use the "using" statement to create an alias for either a class or a namespace.
using Word = Microsoft.Office.Interop.Word;
...
Word.Application = new Word.Application() { Visible = True; }

Thanks : dijksterhuis

Read more tips at C# codes that improve productivity - Part 2

Hope this will help you. A 'Thank You' would be nice!