SlideShare a Scribd company logo
DotNet Programming &
Practices
Dev Raj Gautam
(Active Contributor )
AspNET Community
19th AspNetCommunity Meet-Up
April 19th, 2014
Naming Conventions
• Use Any naming conventions you like.
• Prefix boolean variables, properties and methods with “is” or similar prefixes
• Use PascalCasing for class names and method names, Use camelCasing for method arguments and local variables is in Use.
• Prefix boolean variables, properties and methods with “is” or similar prefixes
• Identifier should tell what it does.
• Prefix interfaces with the letter I.
• Use appropriate prefix for each of the ui element
Example Of Naming Conventions
public class HelloWorld
{
//using Pascal casing for Class and Methods
void SayHello(string name)
{
//functionality for say hello
}
//Camel casing for variables and method parameters
int totalCount = 0;
void SayHello(string name)
{
string fullMessage = "Hello " + name;
}
}
Good:
private bool _isIssued
int salary
IEntity
lblAddress
Bad:
int sal
Proper Documentation and Layout
• Write comments and documentation in US English
• Write XML documentation with another developer in mind
• Avoid inline comments
• Regions can be helpful, but can also hide the main purpose of a class. Therefore,
use #regions only for:
Private fields and constants (preferably in a Private Definitions region).
Nested classes
Interface implementations (only if the interface is not the main purpose of that class)
• Use proper indentation
Method Or Properties?
• If the work is more expensive than setting a field value.
• If it represents a conversion such as the Object.ToString method.
• If it returns a different result each time it is called, even if the arguments
didn‟t change. For example, the NewGuid method returns a different value each
time it is called.
• If the operation causes a side effect such as changing some internal state not
directly related the property
Concise and Unit Job Methods
Example of creating function that do only one job
SaveAddress ( address );
SendEmail ( address, email );
Private void SaveAddress ( string address )
{
// Save the address.
}
Private void SendEmail ( string address, string email )
{
// Send an email to inform that address is changed.
}
• A method should do only 'one
job„, don‟t combine multiple
jobs in single method.
• Don‟t write large methods,
normally 25 lines of the code is
maximum to be included in one
method.
• WHY??
 Increases the maintainability and
reusability of the method
 Reduces the duplicity of code
Reduce the Number of Parameter
Excess parameters reduce method call performance. It is possible to optimize the parameters that a method
receives. We remove unneeded parameters. This will reduce the memory usage on the stack and improve
performance.
Example With Unused arguments
static int Method1(int a, int b, int c, int d, int e, int f)
{
// This method contains extra parameters
that are not used.
if (a == 0)
{
throw new Exception();
}
return a * 100 + b * 10 + c;
}
Example With arguments removed
static int Method2(int a, int b, int c)
{
// This method only contains necessary parameters.
if (a == 0)
{
throw new Exception();
}
return a * 100 + b * 10 + c;
}
Keep Variables private and expose
public/protected Properties
• If you share a member variable between methods, it will be difficult to track
which method changed the value and when.
Properties, methods and arguments representing
strings or collections should never be null
• Returning null can be unexpected by the caller. Always return an
empty collection or an empty string instead of a null reference.
This also prevents cluttering your code base with additional
checks for null.
Should I always return IEnumerable<T> or
ICollection<T>
• IF you don‟t want callers to be able to change an internal
collection, so don‟t return arrays, lists or other collection classes
directly. Instead, return an IEnumerable<T>, or, if the caller must
be able to determine the count return an ICollection<T>
Favor Object and Collection Initializers over
separate statements for Maintainability
What we Do?
var startInfo = new ProcessStartInfo(“myapp.exe”);
startInfo.StandardOutput = Console.Output;
startInfo.UseShellExecute = true;
var countries = new List<string>();
countries.Add(“Netherlands”);
countries.Add(“United States”);
Better
var startInfo = new ProcessStartInfo(“myapp.exe”)
{
StandardOutput = Console.Output,
UseShellExecute = true
};
var countries = new List<string> { “Netherlands”, “United States” };
Local Variable Field Optimization
Incase of frequent access copying the field to local
variable is more efficient
No efficiency
class Program
{
static int _temp1; // Static field
static void Method1()
{
// Increment the static field ten times.
for (int i = 0; i < 10; i++)
{
_temp1++;
}
}
}
Efficient
class Program
{
static int _temp1; // Static field
static void Method2()
{
// Load static field into variable.
// ... Increment that ten times, then copy the value.
int copy = _temp1;
for (int i = 0; i < 10; i++)
{
copy++;
}
_temp1 = copy;
}
}
Avoid LINQ for simple expressions
Rather than
var query = from item in items where item.Length > 0;
prefer using the extension methods from the System.Linq namespace.
var query = items.Where(i => i.Length > 0);
Consider using Any() to determine whether an
IEnumerable<T> is empty
• Use the Any() extension method rather than Count() to determine
whether the collection contains items. If you do use Count(), you
risk that iterating over the entire collection might have a
significant impact.
Explicitly release object references?
• If the object is IDisposable it is a good idea to dispose of it when
you no longer need it, especially if the object uses unmanaged
resources. Not disposing of unmanaged resources will lead to
memory leaks
Using Statement Example
using (MyIDisposableObject obj = new MyIDisposableObject())
{
// use the object here
}
Using Dispose()
MyIDisposableObject obj;
try
{
obj = new MyIDisposableObject();
}
finally
{
if (obj != null)
{
((IDisposable)obj).Dispose();
}
}
Switch Vs IF
Normally Switch Is faster than IF But If the input is almost
always a specific value If preforms better
static bool IsValidIf(int i)
{
// Uses if-expressions to implement selection statement.
if (i == 0 || i == 1)
{
return true;
}
if (i == 2 ||i == 3)
{
return false;
}
if (i == 4 ||i == 5)
{
return true;
}
return false;
}
static bool IsValidSwitch(int i)
{
// Implements a selection statement with a switch.
switch (i)
{
case 0:
case 1:
return true;
case 2:
case 3:
return false;
case 4:
case 5:
return true;
default:
return false;
}
}
Be safe with unexpected values
For example, if you are using a parameter with 2 possible values, never assume that
if one is not matching then the only possibility is the other value
Bad
If ( memberType == eMemberTypes.Registered )
{
// Registered user… do something…
}
else
{
// Guest user... do something…
// If we introduce another user type in future, this code
// will fail and will not be noticed.
}
Better
If ( memberType == eMemberTypes.Registered )
{
// Registered user… do something…
}
else if ( memberType == eMemberTypes.Guest )
{
// Guest user... do something…
}
else
{
// Un expected user type. Throw an exception.
// If we introduce a new user type in future, we can easily // find
the problem here.
}
String Builder Class
Every time the string is concatenated a
new string object Is created
public string ConcatString(string[] lines)
{
string LongString = String.Empty;
for (int i = 0; i < lines.Length; i++)
{
LongString += lines[i];
}
return LongString;
}
String builder is initialized once and on
each concatenation it will get copied to
memory
public string ConcatString(string[] lines)
{
StringBuilder LongString = new StringBuilder();
for (int i = 0; i < lines.Length; i++)
{
LongString.Append(lines[i]);
}
return LongString.ToString();
}
Use static Methods & Static fields
• Non-inlined instance methods are always slower than non-inlined static
methods. To call an instance method, the instance reference must be
resolved, to determine what method to call. Static methods do not use an
instance reference.
• Why Static Methods are Fast?
The static methods can be invoked with fewer instructions
• Why Static Fields are Fast?
Loading an instance field must have the object instance first resolved.
Even in an object instance, loading a static field is faster because no
instance expression instruction is ever use
Exception Handling
• Never do a 'catch exception and do nothing„
• Catch only the specific exception, not generic exception.
Example of catching specific Exception
void ReadFromFile ( string fileName )
{
try
{
// read from file.
}
catch (FileIOException ex)
{
// log error.
// re-throw exception depending on your case.
throw;
}
}
Exception Handling
• Don‟t use large Try Catch Blocks, break the code into multiple try{} Catch{},
this will help to find which piece of code generated the exception and a
specific exception message can be generated to user
• Always use the finally statement to close or deallocate resources
• Provide a rich and meaningful exception message text
Never Hard Code
• Don‟t hardcode string or numbers
• Use constant if you are absolutely sure that the value will never
be changed, config files and database are better place to store
the values.
Build with the highest warning level
• Configure the development environment to use high Warning Level
for the compiler, and enable the option Treat warnings as errors.
• This allows the compiler to enforce the highest possible code
quality.
Thank You

More Related Content

PPTX
Advance topics of C language
PPT
Bad Smell in Codes - Part 1
PDF
Implicit conversion and parameters
PPTX
Intro To C++ - Class #18: Vectors & Arrays
PPT
Scala functions
ODP
Best practices in Java
PPTX
PDF
C++ Templates 2
Advance topics of C language
Bad Smell in Codes - Part 1
Implicit conversion and parameters
Intro To C++ - Class #18: Vectors & Arrays
Scala functions
Best practices in Java
C++ Templates 2

What's hot (13)

PPTX
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
ODP
Functional Programming With Scala
PPTX
Templates presentation
PPTX
Java Generics
PPTX
Java 8 streams
DOC
Java Script Language Tutorial
PDF
Implementing a decorator for thread synchronisation.
PPT
Advanced Javascript
PDF
Refactoring
PDF
Annotation Processing - Demystifying Java's Dark Arts
PPTX
Data Handling and Function
PPT
Synapse india complain sharing info on chapter 8 operator overloading
PPTX
Java 8 Intro - Core Features
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Functional Programming With Scala
Templates presentation
Java Generics
Java 8 streams
Java Script Language Tutorial
Implementing a decorator for thread synchronisation.
Advanced Javascript
Refactoring
Annotation Processing - Demystifying Java's Dark Arts
Data Handling and Function
Synapse india complain sharing info on chapter 8 operator overloading
Java 8 Intro - Core Features
Ad

Viewers also liked (18)

PPTX
ASP .NET MVC Introduction & Guidelines
PPTX
Unit 2 group 5 nucleus science and technology
PPT
Internet by Javiera.
PPTX
Seguridad informatica
PDF
Double cartridge seal
DOCX
sas-course-provider-navi-mumbai-sas-training-navi-mumbai-sas-classes-navi-mumbai
PPT
Основные тренды рынка платного ТВ Украины - Key Trends of Ukrainian Pay TV Ma...
PPTX
The Tao Of Badass Videos
PDF
Single cartridge seal
PPTX
Best java courses in navi mumbai best classes for java in navi mumbai-java cl...
ODP
El sectorterciari pvr
ODT
Activitats la població 11
PPT
Capital steel buildings business opportunities-uk
PPTX
Presentasi 5 group
PPTX
Claudya group 5 physics education b
PDF
E&C Regional telecom market pre M&A analys
PPTX
Best spring classes in navi mumbai,spring course-provider in navi-mumbai,spri...
PPT
Mysql classes in navi-mumbai,mysql course-provider-in-navi-mumbai
ASP .NET MVC Introduction & Guidelines
Unit 2 group 5 nucleus science and technology
Internet by Javiera.
Seguridad informatica
Double cartridge seal
sas-course-provider-navi-mumbai-sas-training-navi-mumbai-sas-classes-navi-mumbai
Основные тренды рынка платного ТВ Украины - Key Trends of Ukrainian Pay TV Ma...
The Tao Of Badass Videos
Single cartridge seal
Best java courses in navi mumbai best classes for java in navi mumbai-java cl...
El sectorterciari pvr
Activitats la població 11
Capital steel buildings business opportunities-uk
Presentasi 5 group
Claudya group 5 physics education b
E&C Regional telecom market pre M&A analys
Best spring classes in navi mumbai,spring course-provider in navi-mumbai,spri...
Mysql classes in navi-mumbai,mysql course-provider-in-navi-mumbai
Ad

Similar to DotNet programming & Practices (20)

PPT
JAVA Tutorial- Do's and Don'ts of Java programming
PPT
JAVA Tutorial- Do's and Don'ts of Java programming
PPTX
C#6 - The New Stuff
PPTX
Back-2-Basics: .NET Coding Standards For The Real World (2011)
PDF
stacks and queues class 12 in c++
PPT
Coding Standards & Best Practices for iOS/C#
PPTX
JAVA LOOP.pptx
PPTX
Certification preparation - Net classses and functions.pptx
PDF
Ds lab handouts
PDF
.Net Classes and Objects | UiPath Community
PPTX
2CPP18 - Modifiers
PPTX
Pi j2.3 objects
PPT
statement interface
PPT
02basics
PPTX
Presentation 2nd
PPSX
Java Tutorial
PDF
Computer science abot c topics array 2d array
PPTX
kotlin-nutshell.pptx
PDF
LECTURE 3 LOOPS, ARRAYS.pdf
PDF
Guava Overview. Part 1 @ Bucharest JUG #1
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
C#6 - The New Stuff
Back-2-Basics: .NET Coding Standards For The Real World (2011)
stacks and queues class 12 in c++
Coding Standards & Best Practices for iOS/C#
JAVA LOOP.pptx
Certification preparation - Net classses and functions.pptx
Ds lab handouts
.Net Classes and Objects | UiPath Community
2CPP18 - Modifiers
Pi j2.3 objects
statement interface
02basics
Presentation 2nd
Java Tutorial
Computer science abot c topics array 2d array
kotlin-nutshell.pptx
LECTURE 3 LOOPS, ARRAYS.pdf
Guava Overview. Part 1 @ Bucharest JUG #1

More from Dev Raj Gautam (8)

PPTX
Protecting PII & AI Workloads in PostgreSQL
PPTX
RED’S, GREEN’S & BLUE’S OF PROJECT/PRODUCT MANAGEMENT
PPTX
Making machinelearningeasier
PPTX
Recommender System Using AZURE ML
PPTX
From c# Into Machine Learning
PPTX
Machine Learning With ML.NET
PPTX
Intelligent bots
PPTX
SOA & WCF
Protecting PII & AI Workloads in PostgreSQL
RED’S, GREEN’S & BLUE’S OF PROJECT/PRODUCT MANAGEMENT
Making machinelearningeasier
Recommender System Using AZURE ML
From c# Into Machine Learning
Machine Learning With ML.NET
Intelligent bots
SOA & WCF

Recently uploaded (20)

PDF
cuic standard and advanced reporting.pdf
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Electronic commerce courselecture one. Pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Sensors and Actuators in IoT Systems using pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Cloud computing and distributed systems.
PDF
Modernizing your data center with Dell and AMD
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Chapter 2 Digital Image Fundamentals.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Advanced Soft Computing BINUS July 2025.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Empathic Computing: Creating Shared Understanding
cuic standard and advanced reporting.pdf
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Electronic commerce courselecture one. Pdf
20250228 LYD VKU AI Blended-Learning.pptx
Understanding_Digital_Forensics_Presentation.pptx
Big Data Technologies - Introduction.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Sensors and Actuators in IoT Systems using pdf
Review of recent advances in non-invasive hemoglobin estimation
Cloud computing and distributed systems.
Modernizing your data center with Dell and AMD
NewMind AI Weekly Chronicles - August'25 Week I
Chapter 2 Digital Image Fundamentals.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Advanced Soft Computing BINUS July 2025.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Per capita expenditure prediction using model stacking based on satellite ima...
Empathic Computing: Creating Shared Understanding

DotNet programming & Practices

  • 1. DotNet Programming & Practices Dev Raj Gautam (Active Contributor ) AspNET Community 19th AspNetCommunity Meet-Up April 19th, 2014
  • 2. Naming Conventions • Use Any naming conventions you like. • Prefix boolean variables, properties and methods with “is” or similar prefixes • Use PascalCasing for class names and method names, Use camelCasing for method arguments and local variables is in Use. • Prefix boolean variables, properties and methods with “is” or similar prefixes • Identifier should tell what it does. • Prefix interfaces with the letter I. • Use appropriate prefix for each of the ui element Example Of Naming Conventions public class HelloWorld { //using Pascal casing for Class and Methods void SayHello(string name) { //functionality for say hello } //Camel casing for variables and method parameters int totalCount = 0; void SayHello(string name) { string fullMessage = "Hello " + name; } } Good: private bool _isIssued int salary IEntity lblAddress Bad: int sal
  • 3. Proper Documentation and Layout • Write comments and documentation in US English • Write XML documentation with another developer in mind • Avoid inline comments • Regions can be helpful, but can also hide the main purpose of a class. Therefore, use #regions only for: Private fields and constants (preferably in a Private Definitions region). Nested classes Interface implementations (only if the interface is not the main purpose of that class) • Use proper indentation
  • 4. Method Or Properties? • If the work is more expensive than setting a field value. • If it represents a conversion such as the Object.ToString method. • If it returns a different result each time it is called, even if the arguments didn‟t change. For example, the NewGuid method returns a different value each time it is called. • If the operation causes a side effect such as changing some internal state not directly related the property
  • 5. Concise and Unit Job Methods Example of creating function that do only one job SaveAddress ( address ); SendEmail ( address, email ); Private void SaveAddress ( string address ) { // Save the address. } Private void SendEmail ( string address, string email ) { // Send an email to inform that address is changed. } • A method should do only 'one job„, don‟t combine multiple jobs in single method. • Don‟t write large methods, normally 25 lines of the code is maximum to be included in one method. • WHY??  Increases the maintainability and reusability of the method  Reduces the duplicity of code
  • 6. Reduce the Number of Parameter Excess parameters reduce method call performance. It is possible to optimize the parameters that a method receives. We remove unneeded parameters. This will reduce the memory usage on the stack and improve performance. Example With Unused arguments static int Method1(int a, int b, int c, int d, int e, int f) { // This method contains extra parameters that are not used. if (a == 0) { throw new Exception(); } return a * 100 + b * 10 + c; } Example With arguments removed static int Method2(int a, int b, int c) { // This method only contains necessary parameters. if (a == 0) { throw new Exception(); } return a * 100 + b * 10 + c; }
  • 7. Keep Variables private and expose public/protected Properties • If you share a member variable between methods, it will be difficult to track which method changed the value and when.
  • 8. Properties, methods and arguments representing strings or collections should never be null • Returning null can be unexpected by the caller. Always return an empty collection or an empty string instead of a null reference. This also prevents cluttering your code base with additional checks for null.
  • 9. Should I always return IEnumerable<T> or ICollection<T> • IF you don‟t want callers to be able to change an internal collection, so don‟t return arrays, lists or other collection classes directly. Instead, return an IEnumerable<T>, or, if the caller must be able to determine the count return an ICollection<T>
  • 10. Favor Object and Collection Initializers over separate statements for Maintainability What we Do? var startInfo = new ProcessStartInfo(“myapp.exe”); startInfo.StandardOutput = Console.Output; startInfo.UseShellExecute = true; var countries = new List<string>(); countries.Add(“Netherlands”); countries.Add(“United States”); Better var startInfo = new ProcessStartInfo(“myapp.exe”) { StandardOutput = Console.Output, UseShellExecute = true }; var countries = new List<string> { “Netherlands”, “United States” };
  • 11. Local Variable Field Optimization Incase of frequent access copying the field to local variable is more efficient No efficiency class Program { static int _temp1; // Static field static void Method1() { // Increment the static field ten times. for (int i = 0; i < 10; i++) { _temp1++; } } } Efficient class Program { static int _temp1; // Static field static void Method2() { // Load static field into variable. // ... Increment that ten times, then copy the value. int copy = _temp1; for (int i = 0; i < 10; i++) { copy++; } _temp1 = copy; } }
  • 12. Avoid LINQ for simple expressions Rather than var query = from item in items where item.Length > 0; prefer using the extension methods from the System.Linq namespace. var query = items.Where(i => i.Length > 0);
  • 13. Consider using Any() to determine whether an IEnumerable<T> is empty • Use the Any() extension method rather than Count() to determine whether the collection contains items. If you do use Count(), you risk that iterating over the entire collection might have a significant impact.
  • 14. Explicitly release object references? • If the object is IDisposable it is a good idea to dispose of it when you no longer need it, especially if the object uses unmanaged resources. Not disposing of unmanaged resources will lead to memory leaks Using Statement Example using (MyIDisposableObject obj = new MyIDisposableObject()) { // use the object here } Using Dispose() MyIDisposableObject obj; try { obj = new MyIDisposableObject(); } finally { if (obj != null) { ((IDisposable)obj).Dispose(); } }
  • 15. Switch Vs IF Normally Switch Is faster than IF But If the input is almost always a specific value If preforms better static bool IsValidIf(int i) { // Uses if-expressions to implement selection statement. if (i == 0 || i == 1) { return true; } if (i == 2 ||i == 3) { return false; } if (i == 4 ||i == 5) { return true; } return false; } static bool IsValidSwitch(int i) { // Implements a selection statement with a switch. switch (i) { case 0: case 1: return true; case 2: case 3: return false; case 4: case 5: return true; default: return false; } }
  • 16. Be safe with unexpected values For example, if you are using a parameter with 2 possible values, never assume that if one is not matching then the only possibility is the other value Bad If ( memberType == eMemberTypes.Registered ) { // Registered user… do something… } else { // Guest user... do something… // If we introduce another user type in future, this code // will fail and will not be noticed. } Better If ( memberType == eMemberTypes.Registered ) { // Registered user… do something… } else if ( memberType == eMemberTypes.Guest ) { // Guest user... do something… } else { // Un expected user type. Throw an exception. // If we introduce a new user type in future, we can easily // find the problem here. }
  • 17. String Builder Class Every time the string is concatenated a new string object Is created public string ConcatString(string[] lines) { string LongString = String.Empty; for (int i = 0; i < lines.Length; i++) { LongString += lines[i]; } return LongString; } String builder is initialized once and on each concatenation it will get copied to memory public string ConcatString(string[] lines) { StringBuilder LongString = new StringBuilder(); for (int i = 0; i < lines.Length; i++) { LongString.Append(lines[i]); } return LongString.ToString(); }
  • 18. Use static Methods & Static fields • Non-inlined instance methods are always slower than non-inlined static methods. To call an instance method, the instance reference must be resolved, to determine what method to call. Static methods do not use an instance reference. • Why Static Methods are Fast? The static methods can be invoked with fewer instructions • Why Static Fields are Fast? Loading an instance field must have the object instance first resolved. Even in an object instance, loading a static field is faster because no instance expression instruction is ever use
  • 19. Exception Handling • Never do a 'catch exception and do nothing„ • Catch only the specific exception, not generic exception. Example of catching specific Exception void ReadFromFile ( string fileName ) { try { // read from file. } catch (FileIOException ex) { // log error. // re-throw exception depending on your case. throw; } }
  • 20. Exception Handling • Don‟t use large Try Catch Blocks, break the code into multiple try{} Catch{}, this will help to find which piece of code generated the exception and a specific exception message can be generated to user • Always use the finally statement to close or deallocate resources • Provide a rich and meaningful exception message text
  • 21. Never Hard Code • Don‟t hardcode string or numbers • Use constant if you are absolutely sure that the value will never be changed, config files and database are better place to store the values.
  • 22. Build with the highest warning level • Configure the development environment to use high Warning Level for the compiler, and enable the option Treat warnings as errors. • This allows the compiler to enforce the highest possible code quality.