This document provides tips and best practices for developing .NET applications. It covers general best practices such as optimization of loops, proper object disposal, and avoiding unnecessary object instantiation. It also includes ASP.NET specific tips like disabling viewstate if not used and avoiding unnecessary round trips to the server. Windows Forms tips involve using multithreading properly and marshaling method calls to the correct thread. The document recommends using existing libraries and not reinventing functionality unnecessarily.
1. Tips and Tricks of Developing
.NET Application
Joni
Applied Technology Laboratories
Bina Nusantara University
2. Agenda
General Best Practices
ASP .NET Specific
Windows Forms Specific
Resources
3. General Best Practices
Looping optimization
ArrayList list = new ArrayList();ArrayList list = new ArrayList();
for(int ifor(int i == 0; i0; i << list.Count; i++)list.Count; i++)
{{
MyObject o = (MyObject)list[i];MyObject o = (MyObject)list[i];
o.DoSomeWork();o.DoSomeWork();
}}
ArrayList list = new ArrayList();ArrayList list = new ArrayList();
MyObject oMyObject o = null;= null;
for(int ifor(int i == 00, n =, n = list.Count; ilist.Count; i << nn; i++); i++)
{{
o = (MyObject)list[i];o = (MyObject)list[i];
o.DoSomeWork();o.DoSomeWork();
}}
4. General Best Practices
Use proper casting, avoid polymorphic call
String s = “Hello world”;String s = “Hello world”;
Session[“key”] = s;Session[“key”] = s;
……
String result = Session[“key”].ToString();String result = Session[“key”].ToString();
String s = “Hello world”;String s = “Hello world”;
Session[“key”] = s;Session[“key”] = s;
……
String result =String result = (string)(string)Session[“key”];Session[“key”];
5. General Best Practices
Acquire, Execute, Release pattern
Works with any IDisposable object
Data access classes, streams, text readers and writers,
network classes, etc.
using (Resource res = new Resource()) {using (Resource res = new Resource()) {
res.DoWork();res.DoWork();
}}
Resource res = new Resource(...);Resource res = new Resource(...);
try {try {
res.DoWork();res.DoWork();
}}
finally {finally {
if (res != null) ((IDisposable)res).Dispose();if (res != null) ((IDisposable)res).Dispose();
}}
6. General Best Practices
static void Copy(string sourceName, string destName) {static void Copy(string sourceName, string destName) {
Stream input = File.OpenRead(sourceName);Stream input = File.OpenRead(sourceName);
Stream output = File.Create(destName);Stream output = File.Create(destName);
byte[] b = new byte[65536];byte[] b = new byte[65536];
int n;int n;
while ((n = input.Read(b, 0, b.Length)) != 0) {while ((n = input.Read(b, 0, b.Length)) != 0) {
output.Write(b, 0, n);output.Write(b, 0, n);
}}
output.Close();output.Close();
input.Close();input.Close();
}}
static void Copy(string sourceName, string destName) {static void Copy(string sourceName, string destName) {
Stream input = File.OpenRead(sourceName);Stream input = File.OpenRead(sourceName);
try {try {
Stream output = File.Create(destName);Stream output = File.Create(destName);
try {try {
byte[] b = new byte[65536];byte[] b = new byte[65536];
int n;int n;
while ((n = input.Read(b, 0, b.Length)) != 0) {while ((n = input.Read(b, 0, b.Length)) != 0) {
output.Write(b, 0, n);output.Write(b, 0, n);
}}
}}
finally {finally {
output.Close();output.Close();
}}
}}
finally {finally {
input.Close();input.Close();
}}
}}
static void Copy(string sourceName, string destName) {static void Copy(string sourceName, string destName) {
using (Stream input = File.OpenRead(sourceName))using (Stream input = File.OpenRead(sourceName))
using (Stream output = File.Create(destName)) {using (Stream output = File.Create(destName)) {
byte[] b = new byte[65536];byte[] b = new byte[65536];
int n;int n;
while ((n = input.Read(b, 0, b.Length)) != 0) {while ((n = input.Read(b, 0, b.Length)) != 0) {
output.Write(b, 0, n);output.Write(b, 0, n);
}}
}}
}}
7. In time critical application, avoid using
‘foreach’
General Best Practices
public static void Main(string[] args) {public static void Main(string[] args) {
foreach (string s in args) Console.WriteLine(s);foreach (string s in args) Console.WriteLine(s);
}}
public static void Main(string[] args) {public static void Main(string[] args) {
for(int i = 0, n = args.Length; i < n; i++)for(int i = 0, n = args.Length; i < n; i++)
Console.WriteLine(args[i]);Console.WriteLine(args[i]);
}}
8. General Best Practices
public ArrayList GetList()public ArrayList GetList()
{{
ArrayList temp = new ArrayList();ArrayList temp = new ArrayList();
……
return temp;return temp;
}}
……
public void DoWpublic void DoWoork()rk()
{{
ArrayList list = new ArrayList();ArrayList list = new ArrayList();
list = GetList();list = GetList();
}}
Avoid unnecessary object instantiation
public ArrayList GetList()public ArrayList GetList()
{{
ArrayList temp = new ArrayList();ArrayList temp = new ArrayList();
……
return temp;return temp;
}}
……
public void DoWork()public void DoWork()
{{
ArrayList list =ArrayList list = nullnull;;
list = GetList();list = GetList();
}}
public ArrayList GetList()public ArrayList GetList()
{{
ArrayList temp = new ArrayList();ArrayList temp = new ArrayList();
……
return temp;return temp;
}}
……
public void DoWork()public void DoWork()
{{
ArrayList list =ArrayList list = GetList()GetList();;
}}
9. General Best Practices
Use StringBuilder for string manipulation
publicpublic stringstring ProcessLongText()ProcessLongText()
{{
string text = “How are you?”;string text = “How are you?”;
string s = text;string s = text;
for(int i = 0; i < 1000; i++)for(int i = 0; i < 1000; i++)
{{
s += text;s += text;
}}
return s;return s;
}}
public string ProcessLongText()public string ProcessLongText()
{{
string text = “How are you?”;string text = “How are you?”;
StringBuilder s = new StringBuilder(text);StringBuilder s = new StringBuilder(text);
for(int i = 0; i < 1000; i++)for(int i = 0; i < 1000; i++)
{{
s.Append(text);s.Append(text);
}}
return s.ToString();return s.ToString();
}}
10. General Best Practices
Do not rely on exceptions in your code
try {try {
result = 100 / num;result = 100 / num;
}}
catch (Exception e) {catch (Exception e) {
result = 0;result = 0;
}}
if (num != 0)if (num != 0)
result = 100 / num;result = 100 / num;
elseelse
result = 0;result = 0;
11. General Best Practices
Don’t reinvent the wheel, unless you are super
programmer, use existing class library
Use Data Access Application Block for
accessing database
objectobject resultresult ==
SqlHelper.ExecuteScalar(connectionString,SqlHelper.ExecuteScalar(connectionString,
CommandType.StoredProcedure, spName, sqlParameters);CommandType.StoredProcedure, spName, sqlParameters);
12. ASP .NET Specific
Disable ViewState if not used
Use output cache to speed-up performance
Disable SessionState if not used
Avoid unnecessary round trips to the server
Use Page.IsPostBack to avoid performing unnecessary
processing on a round trip
Consider disabling AutoEventWireup for your application
<%@ OutputCache Duration=“60" VaryByParam="None" Shared="true" %><%@ OutputCache Duration=“60" VaryByParam="None" Shared="true" %>
<page enableSessionState="true|false|ReadOnly” /><page enableSessionState="true|false|ReadOnly” />
13. ASP .NET Specific
Be sure to disable debug mode
Avoid using DataBinder.Eval
<%# DataBinder.Eval(Container.DataItem, “myfield") %><%# DataBinder.Eval(Container.DataItem, “myfield") %>
<%#<%# ((DataRowView)Container.DataItem)[“myfield”].ToString()((DataRowView)Container.DataItem)[“myfield”].ToString() %>%>
<compilation defaultLanguage="c#"<compilation defaultLanguage="c#" debug=“debug=“falsefalse"" />/>
14. ASP .NET Specific
Override method, instead of attaching delegate
to it
private void InitializeComponent()private void InitializeComponent()
{{
this.Load += new System.EventHandler(this.Page_Load);this.Load += new System.EventHandler(this.Page_Load);
}}
private void Page_Load(object sender, System.EventArgs e)private void Page_Load(object sender, System.EventArgs e)
{{
……
}}
protectedprotected overrideoverride voidvoid OnOnLoad(System.EventArgs e)Load(System.EventArgs e)
{{
……
}}
15. ASP .NET Specific
Use IDataReader instead of DataSet
Use Repeater instead of DataGrid (if possible)
Use the HttpServerUtility.Transfer method to
redirect between pages in the same application
Use early binding in Visual Basic .NET or
JScript code
<%@ Page Language="VB" Strict="true" %><%@ Page Language="VB" Strict="true" %>
16. Windows Forms Specific
Use multithreading appropriately to make your
application more responsive
Windows Forms uses the single-threaded apartment
(STA) model because Windows Forms is based on
native Win32 windows that are inherently apartment-
threaded. The STA model requires that any methods
on a control that need to be called from outside the
control's creation thread must be marshaled to
(executed on) the control's creation thread