Welcome to my blog!


January 3, 2018 14:36

Programming Quotes

Software is not limited by physics, like buildings are. It is limited by imagination, by design, by organization. In short, it is limited by properties of people, not by properties of the world.

C# the maximum number lines of code?

Rule of 30 – When is a Method, Class or Subsystem Too Big?


  • The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that. Functions should not be 100 lines long. Functions should hardly ever be 20 lines long.
  • If an element consists of more than 30 subelements, it is highly probable that there is a serious problem:

    • Methods should not have more than an average of 30 code lines (not counting line spaces and comments).
    • A class should contain an average of less than 30 methods, resulting in up to 900 lines of code.
    • A package shouldn’t contain more than 30 classes, thus comprising up to 27,000 code lines.
    • Subsystems with more than 30 packages should be avoided. Such a subsystem would count up to 900 classes with up to 810,000 lines of code.
    • A system with 30 subsystems would thus possess 27,000 classes and 24.3 million code lines.
  • Complexity metrics are highly correlated with lines of code, and therefore the more complex metrics provide no further information that could not be measured simplify with lines of code.
  • Our goal is to keep our overall system small while we are also keeping our functions and classes small. Remember however that this rule is the lowest priority of the four rules of Simple Design. So, although it’s important to keep class and function count low, it’s more important to have tests, eliminate duplication, and express yourself.

SOLID Principles

SRP: Single Responsibility Principle, There Should Never Be More Than One Reason For A Class To Change 

OCP: Open Closed Principle, Software Entities (Classes, Modules, Functions, Etc.) Should Be Open For Extension But Closed For Modification 

LSP: Liskov Substitution Principle, Functions That Use ... References To Base Classes Must Be Able To Use Objects Of Derived Classes Without Knowing It.

ISP: Interface Segregation Principle, Clients Should Not Be Forced To Depend Upon Interfaces That They Do Not Use 

DIP: Dependency Inversion Principle

  1. High Level Modules Should Not Depend Upon Low Level Modules. Both Should Depend Upon Abstractions
  2. Abstractions Should Not Depend Upon Details. Details Should Depend Upon Abstractions


Refactor code


Software Design principles and design pattern reading


  • Martin Fowler
  • Kent Beck
  • Jeffrey Ritcher
  • Ward Cunningham
  • Scott Hanselman
  • Scott Guthrie
  • Donald E Knuth

5 Tips to Improve Performance of C# Code

  1. Choose your data type before using it:
    • List<int> = new List<int>();
    • int[] arr = new int[100]; //faster
  2. Use For loop instead of foreach
  3. Choose when to use a class and when to use a structure
    • class
    • structure //faster
  4. Always use StringBuilder for String concatenation operations
    • string
    • StringBuilder //faster
  5. Choose best way to assign class data member:
    • public string Name {get; set;}
    • public string Surname; //faster

Lỗi thường gặp trong code của Developer

  • Wrong sizing of available worker threads
  • Loading too much data from database
  • Excessive use of Database Connections
  • Expensive String Concats instead of StringBuilder Usage
  • High Memory Usage due to bad SQL Patterns and String Concats

Question – which of these two is faster?

for (int i = 0; i < _map.Length; i++)
    for (int n = 0; n < _map.Length; n++)
        if (_map[i][n] > 0)

for (int i = 0; i < _map.Length; i++)
    for (int n = 0; n < _map.Length; n++)
        if (_map[n][i] > 0)

Lỗi ở đâu?

DateTime? tmp = new DateTime();
tmp = null;

int? i = new int();
i = null;

object o = new object();
o = null;

Calculate Age of somebody

// Save today's date.
var today = DateTime.Today;

// My birthday
var birthdate = new DateTime(1983, 6, 25);

// Calculate the age.
var age = today.Year - birthdate.Year;

// Go back to the year the person was born in case of a leap year
if (birthdate > today.AddYears(-age)) age--;


Hidden C# Features:




Language Features

Visual Studio Features


Methods and Properties

  • String.IsNullOrEmpty() method by KiwiBastard
  • List.ForEach() method by KiwiBastard
  • BeginInvoke(), EndInvoke() methods by Will Dean
  • Nullable<T>.HasValue and Nullable<T>.Value properties by Rismo
  • GetValueOrDefault method by John Sheehan

Tips & Tricks

  • Nice method for event handlers by Andreas H.R. Nilsson
  • Uppercase comparisons by John
  • Access anonymous types without reflection by dp
  • A quick way to lazily instantiate collection properties by Will
  • JavaScript-like anonymous inline-functions by roosteronacid


C# versions:

These are the versions of C# known about at the time of this writing:

  • C# 1.0 released with .NET 1.0 and VS2002 (January 2002)
  • C# 1.2 (bizarrely enough); released with .NET 1.1 and VS2003 (April 2003). First version to call Dispose on IEnumerators which implemented IDisposable. A few other small features.
  • C# 2.0 released with .NET 2.0 and VS2005 (November 2005). Major new features: generics, anonymous methods, nullable types, iterator blocks
  • C# 3.0 released with .NET 3.5 and VS2008 (November 2007). Major new features: lambda expressions, extension methods, expression trees, anonymous types, implicit typing (var), query expressions
  • C# 4.0 released with .NET 4 and VS2010 (April 2010). Major new features: late binding (dynamic), delegate and interface generic variance, more COM support, named arguments, tuple data type and optional parameters
  • C# 5.0 released with .NET 4.5 and VS2012 (August 2012). Major features: async programming, caller info attributes. Breaking change: loop variable closure.
  • C# 6.0 released with .NET 4.6 and VS2015 (July 2015). Implemented by Roslyn. Features: initializers for automatically implemented properties, using directives to import static members, exception filters, indexed members and element initializers, await in catch and finally, extension Add methods in collection initializers.
  • C# 7.0 released with .NET 4.7 and VS2017 (March 2017) Major new features: tuples, ref locals and ref return, pattern matching (including pattern-based switch statements), inline outparameter declarations, local functions, binary literals, digit separators, and arbitrary async returns.
  • C# 7.1 released with VS2017 v15.3 (August 2017) Minor new features: async main, tuple member name inference, default expression, pattern matching with generics.
  • C# 7.2 released with VS2017 v15.5 (November 2017) Minor new features: private protected access modifier, Span<T>, aka interior pointer, aka stackonly struct, everything else.

There is no such thing as C# 3.5 - the cause of confusion here is that the C# 3.0 is present in .NET 3.5. The language and framework are versioned independently, however - as is the CLR, which is at version 2.0 for .NET 2.0 through 3.5, .NET 4 introducing CLR 4.0, service packs notwithstanding. The CLR in .NET 4.5 has various improvements, but the versioning is unclear: in some places it may be referred to as CLR 4.5 (this MSDN page used to refer to it that way, for example), but the Environment.Version property still reports 4.0.xxx.

More detailed information about the relationship between the language, runtime and framework versions is available on the C# in Depth site. This includes information about which features of C# 3.0 you can use when targeting .NET 2.0. (If anyone wants to bring all of the content into this wiki answer, they're welcome to.)

As of May 3, 2017, the C# Language Team created a history of C# versions and features on their github repo: Features Added in C# Language Versions

Redundant Code = High (mã dư thừa)

ReSharper: Right click on your solution and selection "Find Code Issues". One of the results is "Unused Symbols". This will show you classes, methods, etc., that aren't used.
ReSharper: Find dead .NET code
NDepend: can help to find unused methods, fields and types.
NCover: can help to find Code Coverage.
TestDriven.NET: I use the version of NCover that comes with TestDriven.NET. It will allow you to easily right-click on your unit test class library, and hit "Test With -> Coverage", and it will pull up the report.

Performance Issues = High

What is the best way to debug performance problems?
+ DebugView: You can also write messages in control points using Debug.Write. Then you need to load DebugView application that displays all your debug string with precise time stamp. It is freeware and very good for quick debugging and profiling.

+ Redgate ANTS Performance Profiler: Boost the performance of your applications with .NET profiling

+ Active Directory: Performance Issue - Adding / Removing users from large Active Directory groups in .net

+ Async: Async and LINQ are powerful, but should be used together as carefully and clearly as possible.

+ Other: dotTrace, and AQtime

+ Google: http://www.google.com.au/search?hl=en&q=site:stackoverflow.com+.net+profiler&btnG=Google+Search&meta=&aq=f&oq=

+ The tool I reach for first is PerfMon (Resource and Performance Monitor). Look at key counters like CPU Usage, Memory Usage, Disk and Network I/O.
Generate System Health Report using Perfmon: http://www.thewindowsclub.com/generate-system-health-report-windows-7-8-perfmon
Troubleshoot performance issues in Windows 10/8/7: http://www.thewindowsclub.com/troubleshoot-performance-issues-windows-7
+ The other tools are: Windows Reliability Monitor, System File Checker
+ For SQL problems there’s of course SQL Profiler (find the key queries) and Query Analyzer (view the plans).
Martin Fowler, Kent Beck, Jeffrey Ritcher, Ward Cunningham, Scott Hanselman, Scott Guthrie, Donald E Knuth.

Security Issues = High

Scalability Issues= High

Functional Issues = High

Error Handling = High

OOP in JavaScript and TypeScript

30 year sorting algorithm

WinForm Animation Effect

Data binding concepts in .NET windows forms

Windows Forms: Binding through ITypedList interface


DataGrid: How to build ComboBox, DateTimePicker and Button as User Controls for DataGridColumns for WinForms.

Generic class + Unit Test using Repository & Unit Of Work

PDF & iTextSharp

Multiple language instantly in WinForm

WinForm: A tool for acessing CodeProject and have instant notifications of Codeproject's posts


Optimizing Serialization


C# Advanced
Lecture Notes Part 1 of 4 - An advanced introduction to C#

Lecture Notes Part 2 of 4 - Mastering C#

Lecture Notes Part 3 of 4 - Advanced programming with C#

Lecture Notes Part 4 of 4 - Professional techniques for C#

Utility: Speed Tester

C# Application Programming (HAY HAY HAY)

Desktop GIS Application: Menus & Icons

A one-line program to count lines of code (đếm số dòng code trong tất cả các files)

Why would you use a finally block in an iterator?

Difference between function and method?
A function is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.
A method is a piece of code that is called by a name that is associated with an object. In most respects it is identical to a function except for two key differences:
A method is implicitly passed the object on which it was called.
A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).

Chapter 1: What is Software Architecture?

Chapter 2: Key Principles of Software Architecture

Chapter 3: Architectural Patterns and Styles

Chapter 4: A Technique for Architecture and Design


  • LINQ to Entities
  • LINQ to SQL
  • LINQ to Objects
  • LINQ to DataSet
  • LINQ to XML


Recent posts