Implementing the Singleton Pattern in C#

Essentially, a singleton is a class which only allows a single instance of itself to be created and usually gives simple access to that instance. Most commonly, singletons don’t allow any parameters to be specified when creating the instance, for that This article deals only with the situation where no parameters are required.

There are various different ways of implementing the singleton pattern in C# and I will describe main four ways to implement Singleton Pattern.

First Version: Not Thread Save 

public seald class  singletomInstance {

private singletomInstance (){    }

private static  singletomInstance  _singleInstance =null  ;  

Public  staitc singletomInstance  Instance {


               if(_singleInstance ==null)  {  _singleInstance  = new  singletomInstance() ;   }

                return _singleInstance ;




Second Version: simple thread Save  :

This implementation is thread-safe. The thread takes out a lock on a shared object and then checks whether or not the instance has been created before creating the instance.

public sealed class singletomInstance
private static  singletomInstance  _singleInstance =null  ;  
private static readonly object padlock = new object();

singletomInstance ()  {    }

public static  singletomInstance  Instance
                          lock (padlock)
                                    if (_singleInstance == null)
                                                  _singleInstance new Singleton();
                                           return _singleInstance ;

Third Version: Thread Save by double checking :

This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:

  • It doesn’t work in Java. This may seem an odd thing to comment on, but it’s worth knowing if you ever need the singleton pattern in Java
  •  Without any memory barriers, it’s broken in the ECMA CLI specification too. It’s possible that under the .NET 2.0 memory model (which is stronger than the ECMA spec) it’s safe, but I’d rather not rely on that stronger semantics, especially if there’s any doubt as to the safety. Making the variable Instance volatile can make it work, as would explicit memory barrier calls, although in the latter case even experts can’t agree exactly which barriers are required. I tend to try to avoid situations where experts don’t agree what’s right and what’s wrong!
  • It’s easy to get wrong. The pattern needs to be pretty much exactly as Below- any significant changes are likely to impact either performance or correctness.
  • It still doesn’t perform as well as we need

public sealed class singletomInstance 
private static singletomInstance   _singleInstance null;
private static readonly object padlock = new object();

Singleton(){    }

public static singletomInstance  Instance
if (_singleInstance == null)
lock (padlock)
if (_singleInstance == null)
_singleInstance new Singleton();
return_singleInstance ;


fourth Version: thread save without lock 

public sealed class singletomInstance   
private static readonly  singletomInstance   _singleInstance new  singletomInstance   ();

// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static singletomInstance   ()

private  singletomInstance   ()

public static  singletomInstance   Instance
return _singleInstance ;

As you can see, this is really is extremely simple – but why is it thread-safe and how lazy is it? Well, static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples


How To improve Entity Framework Performance

it is mandatory to know about the performance of it. These are right up to a certain point as LINQ comes with its own penalties. There are some tips and tricks that we should keep in mind while designing and query database using entity framework

Here is a list of some tips you would like to know.

1) Avoid putting all the DB Objects into One Single Entity Model

If we have many database objects that are not connected to one another or these(log tables, objects used by batch processes,etc.) are not used at all. Hence these objects are consuming space in the memory and cause performance degrades. So try to make separate entity models of related database objects

2)Disable change tracking for the entity if not needed

if you need to retrieve the data only for reading purpose then no need for object tracking. disable object tracking by using MergeOption as below

NorthwindDataContext context = new NorthwindDataContext() context.tblCities.MergeOption = MergeOption.NoTracking;

3)Use Compiled Query wherever needed

Make a query to compiled query if it is frequently used to fetch records from the database. This query is slow for the first time but after that, it boosts the performance significantly.

The following example compiles and then invokes a query that accepts a Decimal input parameter and returns a sequence of orders where the total due is greater than or equal to $200.00:

static readonly Func<AdventureWorksEntities, Decimal, IQueryable> s_compiledQuery2 = 
    CompiledQuery.Compile<AdventureWorksEntities, Decimal, IQueryable>(
            (ctx, total) => from order in ctx.SalesOrderHeaders
                            where order.TotalDue >= total
                            select order);

static void CompiledQuery2()
    using (AdventureWorksEntities context = new AdventureWorksEntities())
        Decimal totalDue = 200.00M;

        IQueryable orders = s_compiledQuery2.Invoke(context, totalDue);

        foreach (SalesOrderHeader order in orders)
            Console.WriteLine("ID: {0}  Order date: {1} Total due: {2}",

4)Retrieve the only required number of records

retrieve only required no of records to improve performance. This can achieve by using Take, While and Skip methods.

4)Avoid using Views

Views degrade the LINQ query performance costly. These are slow in performance and impact the performance greatly. So avoid using views in LINQ to Entities

Summary  :

this is some tips to help you improve the performance I hope you enjoy reading  this article and I hop it help you to make your query in a better way

Stored procedure vs Sql function

In SQL Server functions and stored procedure are two different types of entities and every one have its  own features and limitation , for that if we now what are the major  differences between them we can write query on efficient way

I believe that they are both different things they cannot be compared. I can say, it will be like comparing apples and oranges. Each has its own unique use .

This article briefly explain What is a Stored Procedure and what is a Function in SQL Server? It also explains the working and major differences between function and stored procedure in SQL server.


Stored Procedure

A Stored Procedure is nothing more than prepared SQL code that you save so you can reuse the code over and over again. So if you think about a query that you write over and over again, instead of having to write that query each time you would save it as a Stored Procedure and then just call the Stored Procedure to execute the SQL code

User Defined Functions

Like functions in programming languages, SQL Server User Defined Functions are routines that accept parameters, perform an action such as a complex calculation, and returns the result of that action as a value. The return value can either be a single scalar value or a result set.


Types of Functions in SQL Server

There are two types of functions in SQL which are given as following:

Types of Functions in SQL Server

There are two types of functions in SQL which are given as following:

  1. Built-in Functions :The built-in functions are facility provided by the SQL Server to perform several tasks. These functions can also used in T-SQL statements. The built-in function accesses the information from SQL Server system tables without accessing the system tables directly. The built-in functions return value either scalar or table data types.
  2. User-Defined Function : The user defined functions or subroutines performs actions like complex calculation and return results. These functions are made up of one or more T-SQL statements and can be used as to encapsulate the codes for reuse.User-defined functions are created using the Create Function Like :

CREATE FUNCTION function_name( parameter_name  type , parameter_name Type …  ) RETURNS return_data_type [ WITH [ ,..n ] ] [ AS ] BEGIN function_body
RETURN scalar_expression

Types of User Defined Functions

  1. Scalar user defined functionA Scalar user defined function can accept from 0 to many input parameters and a single value will be returned as a result. A scalar UDF can return the results in the form of int, char, and varchar etc..
  2. Inline table valued user defined function: :An inline table-valued user defined function produces data type table variables and its value can be derived from the single select statement. In this function there is no need of begin and end blocks, no need to specify the variables of the tables and not allowed duplicate column names etc.. After declaration of function we can use it as like this.

    SELECT * FROM Fn_GetCityByCountryID(285)

    3. Multi Statement table valued user defined function:This is a different type of function which may contain multiple T-SQL statements. When you want to create a multi statement table valued function then you must need to define the table structure. We can use it in the FROM clause of a T-SQL command.

    After declaration of multi statements table valued user defined function as like this.

    SELECT * FROM  Fn_GetCustomerByCity(285) SELECT * FROM Fn_GetCustomerByCity(1)

Benefits of user defined Functions 

    • They allow modular programming: You can create the function once, store it in the database, and call it any number of times in your program. User Defined Functions can be modified independently of the program source code.
    • They allow faster execution: Similar to Stored Procedures, Transact-SQL User Defined Functions reduce the compilation cost of Transact-SQL code by caching the plans and reusing them for repeated executions. This means the user-defined function does not need to be reparsed and reoptimized with each use resulting in much faster execution times. CLR functions offer significant performance advantage over Transact-SQL functions for computational tasks, string manipulation, and business logic. Transact-SQL functions are better suited for data-access intensive logic.
    • They can reduce network traffic: An operation that filters data based on some complex constraint that cannot be expressed in a single scalar expression can be expressed as a function. The function can then invoked in the WHERE clause to reduce the number or rows sent to the client.

Limitations of User Defined Functions:

  • Unable to modify the databases states.
  • Does not contains OUTPUT INTO clause.
  • A UDF can’t support TRY.. ..CATCH and SET statements.
  • Unable to call a stored procedure (SP), but can call an extended stored procedure(ESP).
  • Can not use dynamic SQL or temp tables, while table variables may use.
  • XML clause is not allowed in user defined functions.

Types of stored Procedure 

there are several four type of stored procedures in SQL. Here I have explained broadly each of them:

  1. User-defined Stored Procedure
  2. System-defined Stored Procedure:
  3. Temporary Stored Procedure:The temporary stored procedure means that it is present in temporary session. This type of stored procedures is prefixed with a hash sign (# ). Where one sign shows that it is present in the temporary session while if it used with double hash sign, this means that the procedure is present globally.
  4. Extended Stored Procedure:Extended stored procedures exist because they allow you to do things that you cannot do with T-SQL like running a DOS command (xp_cmdshell). These stored procedures are routines resides in DLLs which are very similar to the regular stored procedures. The extended stored procedures receives the parameters and return resultant value via SQL Server’s Open Data Services API.
    • Benefits of user Stored Procedures  

      Precompiled execution: SQL Server compiles each Stored Procedure once and then re utilizes the execution plan. This results in tremendous performance boosts when Stored Procedures are called repeatedly.

    • Reduced client/server traffic: If network bandwidth is a concern in your environment then you’ll be happy to learn that Stored Procedures can reduce long SQL queries to a single line that is transmitted over the wire.
    • Efficient reuse of code and programming abstraction: Stored Procedures can be used by multiple users and client programs. If you utilize them in a planned manner then you’ll find the development cycle requires less time.
    • Enhanced security controls: You can grant users permission to execute a Stored Procedure independently of underlying table permissions. 

      Limitations of stored procedure:

      There are also some limitations of stored procedure in SQL which are discussed below:

      • Stored procedure may or not return values.
      • A stored procedure can’t be utilized in selective statements.


​When do you use structs vs classes?

when do we use a struct versus a class? So in C#,
as well as some other object-oriented programming languages,
we have the ability to create a structure in the code or we have
the ability to create a class in the code. And some folks who
are new to dealing with object-oriented programing, or even C#
the ability to create a class in the code. And some folks who
are new to dealing with object-oriented programing, or even C#
in general, are kind of saying, well, a struct in class almost
look the same, why would I use a struct over a class or why would
I use a class over a struct?–m0lBxQYy_504984382

Scoping your Solution Explorer in Visual Studio

You may find this tip very handy and useful in case you are dealing with a large solution with several projects in Visual studio.  We don’t work across the solution / all projects together. and you need to keep focus  to one project in this solution


all what you need to do is  :

    right click the project  and click   ” Scope to This


scope this


and click on the “Back”  , “Forward” or Home button to navigate across.


scope this 3


Similarly you can scoped multiple projects




Along withScope to This” feature you can also leverage “New Solution Explorer viewto create  new instances of Solution Explorer.

With this you will have two different solution explorer as shown in below screenshot.


scope this 2


How to check whether Wi-Fi Connection is enabled on Windows phone

In this short tip I shall be explaining you the simplest way to check the WiFi connection status in Windows Phone. This is a very necessary and required feature for all the apps that use an internet connection.

public bool Checkwificonnection()
bool wificonnection =                 Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsWiFiEnabled;
if (wificonnection)
  return true;
    return false;

c# to singularize – pluralize a word using PluralizationService

in this Post, we will talk about singularize – pluralize a word in c#

first, you have to add a reference  to


using System.Data.Entity.Design ;

let’s go to code …  ^_^

static void Main()
Consol.writeLine(string.Format("this is Pluralize for apple {0}" ,Pluralize("apple") )) ; 

Consol.writeLine(string.Format("this is Singularize for cars {0}" ,Singularize ("cars") )) ;


// this method is useing PluralizationService  Pluralize methos to  Pluralize  the word 

protected string Pluralize(string tablename)
var  _Plurale= PluralizationService.CreateService(new System.Globalization.CultureInfo(“en-us”));

return _Plurale.Pluralize(tablename);
protected string Singularize (string tablename)
var Singular= PluralizationService.CreateService(new System.Globalization.CultureInfo(“en-us”));

return Singular.Singularize(tablename);

#MVC Models creator

MVC models Creator  

its tool  that can help developers to develop MVC application without take Care about building  models from Database  the heavy work of putting data annotation attribute like required or maximum length attribute

its easy to use  see the image

enter your server credential
seelect your databse that you need to generate classes from its tables
press on generate button
select your folder you want to save files in
proccess complete
generated class
generated resource for the class


dnu restore problem

If dnu restore is not a recognized command, you may have missed a prerequisite step


so you have to do some steps   then you can use the command

  1. Install Visual Studio 2015

Be sure to specify that you want to include the Microsoft Web Developer Tools.


  1. Install ASP.NET 5.
This will install the latest ASP.NET 5 runtime and tooling.
  1. Enable the ASP.NET 5 command-line tools. Open a command-prompt and run:

    > dnvm upgrade


  1. On Windows 7 and Windows Server 2008 R2 you will also need to install the Visual C++ Redistributable for Visual Studio 2012 Update 4.

jQuery Tips Everyone Should Know

A collection of simple tips to help you  In   jQuery .

Back to Top Button

By using the animate and scrollTop methods in jQuery you don’t need a plugin to create a simple scroll-to-top animation:

$('').click(function (e) {
  $(document.body).animate({scrollTop: 0}, 800);
<!-- Create an anchor tag -->
<a class="top" href="#">Back to top</a>


Fix Broken Images Automatically

$('img').on('error', function () {
  $(this).prop('src', 'img/broken.png');

Stop the Loading of Links

Sometimes you don’t want links to go to a certain web page nor reload the page; you might want them to do something else like trigger some other script. This will do the trick of preventing the default action:

$('').click(function (e) {

Make Two Divs the Same Height

Sometimes you’ll want two divs to have the same height no matter what content they have in them:

$('.div').css('min-height', $('.main-div').height());

Open External Links in New Tab/Window

Open external links in a new browser tab or window and ensure links on the same origin open in the same tab or window:


Note:window.location.origin doesn’t work in IE10. This fix takes care of the issue.

Find Element By Text

By using the contains() selector in jQuery you can find text in content of an element. If text doesn’t exists, that element will be hidden:

var search = $('#search').val();

Trigger On Visibility Change

Trigger javascript when the user unfocuses or refocuses on a tab.

$(document).on('visibilitychange', function(e){
  if ( === "visible") {
    console.log('Tab is now in view!');
  } else if ( === "hidden") {
    console.log('Tab is now hidden!');
for more information see this  :