How to create C# Utility Class? - ASP.net
What is Utility Class?
A Utility Class is a set of methods that perform common, often re-use functions. It may contains static functions but no attributes. I will explain you with an example of C# Utility Class and how to use this util class in ASP.net web application. Find the web project source below :-
utility class in c# |
<connectionStrings>
<add name="myConnString" connectionString="Server=localhost;Initial Catalog=OnlineShopping;Integrated
Security=True"/>
</connectionStrings>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
namespace WebDemo_Utility
{
public sealed class Util // sealed to ensure the
utility class won't be inherited
{
private Util() { } //
Ensure you cannot instantiate an object of this type
//Add
static methods which means you can reference them
//anywhere
in the project simply by using Util.
//This
one keeps the name of the connection string in just 2 places -
//once
in the Web.Config, and once in the Util class.
public static string GetConnString()
{
return WebConfigurationManager.ConnectionStrings["myConnString"].ConnectionString;
}
}
}
To use this method is simple. Whenever a connection object is created one of the arguments passed to the constructor is the connection string. This is done as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebDemo_Utility
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connectionString = Util.GetConnString();
Response.Write(connectionString);
}
}
}
Download Code
I hope you will enjoy the development tips while developing asp.net web application. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome. Also If you like this article, don't forget to share this article with your friends and colleagues.
How to create C# Utility Class? - ASP.net
Reviewed by Ravi Kumar
on
12:41 AM
Rating:
No comments: