TechBubbles

Archive for the 'C#' Category

C# IDE Tips & Tricks Part 2

This post explains the some more tips on using Visual C# IDE to enhance developer productivity.

  • Solution Configurater  Right click your solution in your IDE then select the ConfigurationManager  you see the following window

 cmtemplate

where you have the option to select the project for building. We can select the required project in the solution and can you can build the project.

  • Solution Wide Comments You can add task lists and comments to your solution. To view the task list for your solution select view menu and click on TaskList option. Ctrl + W, T you will see the following window

tasklist

You can add the task list items to window by writing the following snippet in the code file.

Read more

1 comment

Singleton Design Pattern in C#

Best known Creational Design Pattern is Singleton. We can implement this pattern in different ways. I am explaining some of the ways where we can implement in C#.

We will have the following concepts in implementing the Singleton pattern

  • We declare a private constructor which prevents other classes to create an instantiation of the singleton class. It also prevents the sub classing.
  • We declare a class as sealed so that it can not be instantiated.
  • We declare a static variable for holding the reference of a singleton class.
  • We declare a public property to return the singleton instance.
  • We declare a method for returning the message from the singleton class.

Singleton

The problem with the above code is it is not a thread –safe code. For example if two threads evaluates the if condition in the above code and both returns the true.

We will rewrite the code for thread safety

SingletonLock

The above implementation is thread safe but having the performance issue.

Every time the lock is acquired whenever you request the object.

We can write the above code with out implementing the locks as follows

image

The static constructor in C# only be called whenever you create a instance for the class.

No comments

C# IDE Tips & Tricks Part 1

C# Developers have been spending most their day activities

with Visual studio IDE. They may have to understand the following activities to do their job.

  • Understanding Code Developer must be able analyze the relationship between classes and what API it is using for implementing the logic.
  • Navigating Code Developer may or may not know where he want to navigate to the code and keep track of visited files in the code.
  • Writing & Modifying Code Developers may require to modify the existing code like refractoring which involves make the code readable and fix bugs etc
  • Debugging & Testing Understanding the using of debugger tools and writing unit test cases.

Visual studio provides the tools for all the activities mentioned above to make the developer efficient and productive. This post speaks about using the tools available in VS 2008 sp1. It also discusses about the tool coderush express which Microsoft partnering and allows the developers to download and use freely.

 Download Coderush for C#

1. One of the short cut for goto definition is F12

For example you have an identifier and you want to know where it is declared just press F12. If the identifier is not your project then it shows the metadata of the identifier. eg we are viewing string class

Untitled 

Read more

1 comment

C# ?? operator

The ?? operator in C# called null-coalescing operator is used to define a default value for a nullable value types and reference types. It returns the left-hand operand if it is not null and returns right-hand operand if it is null.

example

// ?? operator example

. int? x = null;

int y = x ?? –1;

// Here the value of y will be –1.

int i = GetValue() ?? default(int);

Assigns the return value of the method to i if  return value is not null other wise it assigns default value

It can be used with reference type as follows

string s = GetStringValue(); // ?? also works with reference types. // Display contents of s, unless s is null, // in which case display "Unspecified". Console.WriteLine(s ?? "Unspecified");

No comments

Using keyword in C#

Introduction

Using keyword in C# can be used as directive and as well as statement.

When you use using as Directive you will get the following advantages

  • You can use the types in a namespace by declaring with using keyword.

        example: using Systetm.Web;

 

  • You can define a alias for the nested namespaces

       example: using alias = CompanyName.ProjectName;

When you use using as Statement it defines the scope and allows the programmer to release the resources used by the object in the defined scope.

The object mentioned in the using statement must implement IDisposable interface. A using statement is can be exited when the end of the using statement is reached.

example :

Font font2 = new Font("Arial", 10.0f);
using (font2)
{
    // use font2
}
Multiple objects can be used in with a using statement, but they must
be declared inside the using statement.

example:

using (ResourceType r1 = e1, r2 = e2, …, rN = eN) statement

it is equivalent to the following code

using (ResourceType r1 = e1)

   using (ResourceType r2 = e2)

      …

         using (ResourceType rN = eN)

            statement

No comments

The Future of C#

Introduction

This post speaks about the future of C# which presented by Anders Hejlsberg chief architect of C# at PDC 2008. The coming version 4.0 is much concerned on introducing Functional and Dynamic programming language concepts into the C#. It also speaks about 4.0 features.

EvalC#

The factors that shape the 4 are

  • Declarative programming
  • Dynamic programming
  • Concurrence programming

Read more

1 comment

Lambda Expressions in C# 3.0

Lambda expressions is one of the features introduced in the C# 3.0. Lambda expressions help you to ease the burden of writing verbose Anonymous Methods.

I will explain the where to use the Anonymous methods first then we see the example on lambda expressions

Anonymous Methods

Anonymous Methods is the feature in C# 2.0. The idea behind writing the anonymous methods is to write methods inline to the code with out declaring a formal named method. Normally they used for small methods that don’t require any reuse.

Example:

class TestProgram

{

   static void Main( string[] args )

   {

      List<string> names = new List<string>();

      names.Add(“Kalyan”);

      names.Add(“Suresh”);

      names.Add(“Naveen”);

      string strResult = names.Find(IsKalyan);

   }

   public static bool IsKalyan(string name)

  {

      return name.Equals(“Kalyan”);

  }

}

You can declare a anonymous method as follows

class TestProgram

{

   static void Main( string[] args )

   {

      List<string> names = new List<string>();

      names.Add(“Kalyan”);

      names.Add(“Suresh”);

      names.Add(“Naveen”);

      string strResult = names.Find(delegate (string name )

                                            {

                                                return name.Equals(“Kalyan”);

                                             }   );

   }

}

Advantage: It saves some typing and puts the method closer to where it is being used which helps with maintenance

Lambda Expressions

Lambda Expressions makes the thing even more easier by allowing you to write avoid anonymous method and statement block.

class TestProgram

{

   static void Main( string[] args )

   {

      List<string> names = new List<string>();

      names.Add(“Kalyan”);

      names.Add(“Suresh”);

      names.Add(“Naveen”);

      string strResult = names.Find( name => name.Equals(“Kalyan”));

}

We can also effectively use the Lambda Expressions with LINQ and i will explain the feature in forth coming articles.

No comments

Object and Collection Initializers Feature in C# 3.0

C# 3.0 introduced the another interesting feature Object and Collection initialization expressions.

Object Intialization  Expressions allows you to initialize an object without invoking the constructor and setting its properties.

If you take Employee Class as an Example:

public class Employee {
private int iEmpId;
private string strFirstName;
private string strLastName;

public int ID{
get{
return iEmpId;
}
}

public string FirstName {
get {
return strFirstName;
}
set {
strFirstName= value;
}
}

public string LastName {
get {
return strLastName;
}
set {
strLastName = value;
}
}

 public Employee() {}
}

We can use Object Intialization Expressions in C#3.0 Features  to create a Employee as follows:

Employee objEmployee  = new Employee {ID=007, FirstName = “Kalyan” LastName = “Bandarupalli” }

Now observe the above code we have neither  invoked the constructor nor set the any properties directly. The code above is equivalent to the following code:

 

Employee objEmployee = new Employee();

objEmployee.ID = 007;

objEmployee.FirstName = “Kalyan”;

objEmployee.LastName = “Bandarupalli”;

We can use Collection Intialization Expressions in C#3.0 Features  to create a list of Employees as follows:

 

List<Employee> listofEmployees  = new List<Employee>

{  {objEmployee.ID = 007,  objEmployee.FirstName = "Kalyan”},

     {objEmployee.ID = 007,  objEmployee.FirstName = "Suresh”},

    {objEmployee.ID = 007,  objEmployee.FirstName = "Naveen”}

  };

The advantage of using this feature is that it saves your time for creating a lot of constructors or initializing the individual property.                    

2 comments

Automatically Implemented Properties Feature in C# 3.0

Introduction of Automatic Properties in C# 3.0 make property declaration more concise. It saves some of your time in typing a lot of code.

Example:

class Employee
{
public string FirstName { get; set; }
}

Benefit of using Automatic Properties

We have been creating properties in so many projects and notice that we are writing so many lines of code just for creating a simple property.

Example: Employee class that does not use Automatic Properties

public class Employee {
private int iEmpId;
private string strFirstName;
private string strLastName;

public int ID{
get{
return iEmpId;
}
}

public string FirstName {
get {
return strFirstName;
}
set {
strFirstName= value;
}
}

public string LastName {
get {
return strLastName;
}
set {
strLastName = value;
}
}
}

In order to create a simple property, we are coding extra four or five lines code. So, if we have 100 properties in different entity classes, we have to  type too much of code just for creating properties.

If you convert above Employee class with Automatic properties it look like

class Employee
{
public int ID{ get; private set; } // read-only
public string FirstName { get; set; }
public int LastName { get; set; }
}

Note: This is my first article to explain the C# 3.0 tutorial series. 

Conclusion

It is one of C# 3.0 Language feature and nothing new except it helps you to improve your productivity.

2 comments

Test driven development using C#

This post explains how TDD can be implemented in C# using NUNIT.

You can read the Introduction TDD to get an idea on TDD.

Nunit is a open source framework to for .NET which helps you to automate the unit testing. Nunit can downloaded from the Nunit site. current version is 2.5.

Nunit provides two utilities for running the automated tests

  • nunit-gui.exe – GUI tool
  • nunit-console.exe – Command line tool

Using Nunit in Visual studio .NET Project

To implement the TDD we need to write

  1. Test cases
  2. program that is having test cases to run against it

Behavior of the Person C# class that we are going to write test cases

The Behavior can be described as follows

  • A Person has properties age,full name and cash balance.
  • When instantiating a person we should able to provide a first name, last name and age.
  • The person full name property should return first name and last name with a space in-between.
  • When you are creating person object cash balance should be 20000.
  • The cash balance should be reduced by the amount he with draws.

From the Above behavior we can formulate a number of test cases example

  • If we create a person with first and last name of “Kalyan” and “Bandarupalli” , and age 27, the person’s full name should not be ” Kalyan Hero”.
  • The person full name should be “Kalyan Bandarupalli”.
  • The person’s age should be 27.
  • Before withdrawing money the person’s cash balance should be 20000.
  • After withdrawing 10000 cash, the person’s cash balance should be 10000.

We can implement the above test case in code[C#] using Nunit. To create a test case in your application create a class having the [TextFixture] attribute.

This class will contain test to test the methods,operations and values in    Person   class.

Read more

No comments

Next Page »