Category Archives: .NET General
Method Overloading
Polymorphism is one of the main characteristics of Object Oriented Programming (OOP). Put simply, it allows an object to behave in various ways depending on the manner in which it is used. For example, you could have a method execute differently based on the type and/or number of parameters passed to it. Method Overloading is what makes this example possible. To accomplish Method Overloading, a developer can define two or more methods with the same name. Each method will take a different set of parameters. The parameter combination or signature, is what the compiler uses to determine which method to use.

Good examples of Method Overloading in the .NET Framework include (but are not limited to) the Console.WriteLine() and Substring() methods. You can pass different types to the Console.WriteLine() method and it will work because there are variations of the methods that will accept the different types.

–
C# Program
using System; namespace MethodOverloading { class Program { static void Main(string[] args) { MethodOverloadPlay(10, 3); Console.WriteLine("+++++"); MethodOverloadPlay(5, 5, 6); Console.WriteLine("+++++"); MethodOverloadPlay("SP"); Console.ReadLine(); } static void MethodOverloadPlay(int number1, int number2) { int result = number1 + number2; Console.WriteLine(result); } static void MethodOverloadPlay(int number1, int number2, int number3) { int result = number1 + number2 + number3; Console.WriteLine(result); } static void MethodOverloadPlay(string string1) { Console.WriteLine("Breaking Benjamin & Sick Puppies Rock!"); } } }
–
Result

–
The main advantage of Method Overloading is code readability. Programming languages that do not allow Method Overloading require the developer to create totally separate methods for each variation of the input. Blackwasp Consulting states the following example: in the ANSI C programming language to truncate a value you would use trunc, truncf or truncl according to the data type being rounded. In C#, method overloading allows you to always call Math.Truncate.
–
Additional Information
- C# Method Overloading – BlackWasp Consulting
- Guidelines for Method Overloading – Dave Donaldson
- Method overloading – CSharp .Net-tutorials
- Method overloading in C# .Net – Coder Source
–
^..^
Timers in .NET
I was researching timers the other day and realized that there are three variations in the .NET Framework.

The three types of timers are explained below.
1 – System.Timers.Timer
The System.Timers.Timer class timer is considered a server-based timer that was designed and optimized for use in multithreaded environments. It can be accessed safely from multiple threads.
C# Program
using System; using System.Timers; public class Program { private static System.Timers.Timer testTimer; public static void Main(string[] args) { testTimer = new System.Timers.Timer(5000); // 5 seconds testTimer.Elapsed += new ElapsedEventHandler(OnTimerElapsed); testTimer.Interval = 5000; testTimer.Enabled = true; Console.WriteLine("Press the enter key to stop the timer"); Console.ReadLine(); } private static void OnTimerElapsed(object source, ElapsedEventArgs e) { Console.WriteLine("Timer elapsed at {0}", e.SignalTime); } }
Output

–
2 – System.Threading.Timer
The System.Threading.Timer class timer uses a TimerCallBack Delegate to specify the associated methods. The methods do not execute in the thread that created the timer; they execute in a separate thread that is automatically allocated by the system.
C# Program
using System; using System.Threading; class Program { static void Main() { AutoResetEvent reset = new AutoResetEvent(false); StatusChecker status = new StatusChecker(5); // Invoke methods for the timer via a Delegate TimerCallback timerDelegate = new TimerCallback(status.CheckStatus); // Create a timer that signals the delegate to invoke // Check status after one second, and then every 1/4 second Console.WriteLine("{0} Creating the timer.\n", DateTime.Now.ToString("h:mm:ss.fff")); Timer stateTimer = new Timer(timerDelegate, reset, 1000, 250); // When the auto reset executes, change to every 1/2 second reset.WaitOne(5000, false); stateTimer.Change(0, 500); Console.WriteLine("\nChanging the timer period.\n"); reset.WaitOne(5000, false); stateTimer.Dispose(); Console.WriteLine("\nDestroying the timer."); } } class StatusChecker { int invokeCount, maxCount; public StatusChecker(int count) { invokeCount = 0; maxCount = count; } // This method is called by the timer delegate. public void CheckStatus(Object stateInfo) { AutoResetEvent autoEvent = (AutoResetEvent)stateInfo; Console.WriteLine("{0} Checking status {1,2}.", DateTime.Now.ToString("h:mm:ss.fff"), (++invokeCount).ToString()); if (invokeCount == maxCount) { // Reset the counter and signal Main. invokeCount = 0; autoEvent.Set(); } } }
Output

–
3 – Windows.Forms.Timer
The Windows.Forms.Timer class works synchronously with the Windows Form, so that it will not interrupt any operations. It initializes on the UI thread.
C# Program
using System; using System.Windows.Forms; namespace WindowsFormsTimer { public class Class1 { static System.Windows.Forms.Timer theTimer = new System.Windows.Forms.Timer(); static int alarmCounter = 1; static bool exitFlag = false; // Timer raised method private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs) { theTimer.Stop(); // Displays a message box asking whether to continue to run the timer if (MessageBox.Show("Continue running?", "Count is " + alarmCounter, MessageBoxButtons.YesNo) == DialogResult.Yes) { // Restarts the timer and increments the counter alarmCounter += 1; theTimer.Enabled = true; } else { // Stops the timer exitFlag = true; } } public static int Main() { //Adds the event and the event handler for the method that will //process the timer event to the timer theTimer.Tick += new EventHandler(TimerEventProcessor); // Sets the timer interval to 5 seconds theTimer.Interval = 2000; theTimer.Start(); // Runs the timer, and raises the event while (exitFlag == false) { // Processes all the events in the queue Application.DoEvents(); } return 0; } } }
Output

–
There are three choices for timers in .NET. It just depends on what you want to do.
–
More Information
- Comparing the Timer Classes in the .NET Framework Class Library
- System.Timers.Timer vs System.Threading.Timer
- Working with Timer Control in VB.NET
–
Until next time…
^..^
HDNUG – October/09 Meeting – Recap
I attended the Houston .NET User Group October ’09 meeting last night. There was a good turnout of about 75-85 people in attendance.
Announcements -
- Next month Zain Naboulsi will be presenting on Windows 7 for developers
- There is an upcoming ASP.NET User Group that will likely be on the 4th Tuesday of each month – no dates set yet
Main topic -

Claudio Lassala gave a great talk titled Be a Professional Developer and Write Clean Code. Below are some of the points covered.
- What is clean code? Elegant and efficient, can be read and enhanced, simple and direct, etc…
- Computers do not care what your code looks like
- Name variables so that you don’t need comments
Instead of –
//Setting employee’s first name
string field1 = “Rhonda” ;
Use this –
string employeeFirstName = “Rhonda”;
- If you have source control, there is no reason to keep code commented
- NDepend – a good tool that provides metrics for your code
- Functions should do one thing and do it well
- Vertical Distance – Declare variables close to where they are used. There is no need to declare all variables at the top of the program.
Presentation Materials for Be a Professional Developer and Write Clean Code
There were a lot more great points, but I had to leave before Claudio was finished. He did a great job of explaining how bad code should be rewritten.
Looking for a user group meeting to attend? Check out my Houston Tech Groups and Events page.
–
Until next time…
^..^
Houston TechFest 2009 – Recap

I attended the Houston TechFest last weekend and I have to say it was a great turnout. According to the web site there were 858 people in attendance. There were 14 tracks containing 70+ sessions.
–
Below are the sessions that I attended and some notes I took along the way.
What’s New In Silverlight 3.0

Presenter: Todd Anglin
This presentation gave a great high-level explanation of Silverlight 3.0 and Rich Internet Applications.
Silverlight is not (nor will be anytime soon) available for the iPhone. Apple does not allow this type of plugin.
High Points of Silverlight 3.0
- GPU Acceleration
- Out of Browser (Fit Client)
- Search Engine Optimization (SEO)
- Assembly Caching
- Validation Templates
- SaveFileDialog
- Cached Composition
- Network Monitoring
- 3-D Support
What’s New in Silverlight 3.0 – Slides and Demo Code
Introduction to iPhone Development

Presenter: Ben Scheirman
This presentation covered the requirements for developing on the iPhone as well as some syntax and frameworks.
Requirements
- A Mac
- X-Code (free)
- iPhone SDK (free – limited to simulator)
- iPhone Developer Program ($99)
Language – Objective C
Based on C, Dynamic, Object Oriented, Powerful
Ben provided a great primer on Objective C. I have to say, it is quite different from any syntax I have ever encountered.
[photo setCaption : @"Day at the beach."];
NSString* caption = [photo caption];
Some of the topics touched on in the primer
- Multi-Input
- Accessors
- Memory Management
- Header Files
- Implementation Files
- Categories (like extension methods)
- Key Value Coding (like reflection)
Frameworks and Libs
- Cocoa Touch
- AddressBook
- Camera
- Accelerometer – Tilt/Gravity
- Magnetometer – Direction
- MapKit – Embedded maps
- CoreLocation – GPS
- CoreGraphics – High level graphics
- CoreAnimations – High level animations
- OpenGL ES – 3D graphics
Introduction to iPhone Development – Slides and Demo Code
Evolve Your Code Using Extension Methods, Fluent Interfaces and Expressions
![]()
Presenter: Jonathan Birkholz
This presentation thoroughly covered the topics of Extension Methods, Lambda Expressions and Fluent Interfaces.
Points explored
- Extension Methods – Methods added to existing types. They are static methods, but called as if they were instance methods.
- Lambda Expressions – Anonymous functions that can contain expressions and statements.
- Expression Trees – Representation of language level code in the form of data.
- Expression Tree Visualizer – working implementation of a visualizer that can be run inside the Visual Studio debugger to view the contents of an expression tree.
- Fluent Interfaces – Way of implementing an object oriented API (DSL) in a way that provides more readable code.
- Single Responsibility Principle – A class should have 1 and only 1 reason to change.
Tools discussed
- StructureMap – Dependancy Injection/Inversion of Control tool
- Fluent nHibernate – Fluent, XML-less, compile safe, automated, convention-based mappings for NHibernate.
- AutoMapper – A convention-based object-object mapper.
- NBuilder – Tool for rapidly creating test data. I am really interested in this tool…
Evolve Your Code – Slides and Demo Code
Developer <T>: Utilizing .Net Generics to Write Better Code
![]()
Presenter: Shawn Weisfeld
This presentation provided a great overview of .NET Generics.
Generics are basically type-safe data structures that do not commit to a data type. This feature was introduced in .NET Framework 2.0/Visual Studio 2005.
Other points covered
- Generic Contraints
- Generic Lists
- Generic Structs
- Generic Guidelines
- Performance
Resources provided
- Teach Yourself Visual C# 2010 in 24 Hours
- An Introduction to C# Generics
- Professional .NET 2.0 Generics
Utilizing .NET Generics to Write Better Code – Slides and Demo Code
–
Materials for all the sessions are being posted to the TechFest 2009 Content site.
The 2009 Houston TechFest was a great day of learning and I am already looking forward to next year. As always, the swag was pretty nice too.
–
Until next time…
Stripping the Decimal From a Value in .NET
I am working on a project in which the final output is an EDI file that is translated into claims by the state. I had an issue in which I needed to strip the decimal point from both amount and diagnosis code fields. They also need to be right justified and padded with zeroes. (ie, 123.98 = 00012398)
Coming from a Visual FoxPro background, I knew how to do this in that language, but not in C#. I was able to accomplish my task by using the Replace and PadLeft methods which can be found in String Class.
C# Program
using System; namespace StripDecimal_CS { class RemoveDecimal { static void Main(string[] args) { double testNum = 255.95; string noDecimalVal = testNum.ToString().Replace(".", "").PadLeft(9, '0'); Console.WriteLine("Original Value: " + testNum.ToString()); Console.WriteLine("Value w/No Decimal: " + noDecimalVal); } } }
VB.NET Program
Imports System Namespace StripDecimal_VB Class RemoveDecimal Shared Sub Main(ByVal args As String()) Dim testNum As Double = 255.95 Dim noDecimalVal As String = _ testNum.ToString().Replace(".", "").PadLeft(9, "0"c) Console.WriteLine("Original Value: " + testNum.ToString()) Console.WriteLine("Value w/No Decimal: " + noDecimalVal) End Sub End Class End Namespace
The Result
–
Until later…
SHDNUG Meeting – 03/04/09 – Recap
I attended the 2nd South Houston .NET User Group meeting earlier this week. This is a new group, so the attendance was light, but the content was anything but.
Aaron Dargel with Sogeti did a great job by keeping the PowerPoint slides to a minimum and coding to a maximum. The topic was C# 3.0 Deep Dive…and deep dive was the truth. He kept using the phrase “down the rabbit hole” which was fitting for some of the code he was presenting. You could keep adding to it, going deeper and deeper…like a rabbit hole.
Aaron started off by explaining how everything is on a different version number.
- C# Compiler is at 3.0
- DotNet Framework is at 3.5
- The CLR is at 2.0
–
The C# 3.0 features mentioned & demonstrated
Implicitly Typed Local Variables
You do not have to declare a variable type implicitly. (var aString = “Rhonda” instead of string aString = “Rhonda”)
Object and Collection Initializers
- Nameless class type that inherits directly from an object
- Infers the type based on what is assigned – can’t assign ‘null’ because it is not know what type ‘null’ is
- Static method you can invoke using instance method syntax
- An existing method can be overloaded with an extension method
- Instance method takes precedence
Lamda Expressions – Shorter way of writing Anonymous Methods
–
Related Links
- C# 3.0 Specifications – everything you ever wanted to know about C# 3.0
- Extension Method .NET - a database of C# 3.0 and Visual Basic 2008 extension methods. It contains many user-rated extension methods that will expand your code library immediately.
Book Review: Microsoft Visual Studio Tips (Awesome Book)
Microsoft Visual Studio Tips: 251 Ways to Improve Your Productivity
Author: Sara Ford
Publisher: Microsoft Press
No. Pages: 229
I pre-ordered the this book back in August and I have to say this is the best book on the Visual Studio IDE that I have ever run across. It is a great collection of tips taken from Sara Ford’s ever-popular Visual Studio Tip of the Day. I really like the “Sara Aside” sections where extra insight is given about the tip.
There are tips for (but not limited to) the following -
- Dealing with the editor
- Searching files
- Development environment
- Debugging
- Design time tools
If you have to spend any amount of time in Visual Studio then this book is definitely worth the money as I will be referring back to it time and time again. I am also recommending it at my office. Especially for beginners to .NET.
Happy Reading.
Good Development Resource – DevMavens
While making my first skim through the newest issue of CoDe Focus I ran across an advertisement for a web site called DevMavens. This site looks like a great resource for keeping up with the best of the best in application development.
So far it includes influential developers like Scott Guthrie, Jeff Atwood, Scott Hanselman, Jeffery Palermo among several others. The site is an aggregation of their Blogs and Twitter posts which make it a great place to keep up with what the development community leaders are saying everyday.
HDNUG Meeting – 10/09/08 – Recap
I attended last night’s Houston .NET User Group meeting and with a lighter crowd than normal still proved to be an informative session. There were about 60 people in attendance.
Some of the announcements made -
- Speaker for November will be Bill Daugherty on the topic of Web Services Software Factory
- Houston TechFest has been rescheduled for 1/24/2009
- Speaker for the October C# SIG will be Rod Paddock on the topic of Data Manipulation & Silverlight (I think)
- Markus Egger is putting on another State of .NET presentation on 11/10/09 from 1:00-5:00
- New Designer/Developer SIG – Inaugural meeting is on 11/6/09. Will normally be on the 1st Tuesday of each month. Inaugural meeting is on a Thursday due to Tuesday being Election Day and all…
- Some individuals are working on putting together an ASP.NET user group. Should hear more over next couple of months.
The speaker was Mike Azocar and his topic was Scrum-tastic Development with Visual Studio Team System and Light Weight Scrum. It seems like a really heavy topic, but he did a great job getting through the major aspects of the topic.
He talked about how 2/3 of projects are either really challenged for fail outright. Team System is a platform of tools to help assist teams to have better communication and general work flow. The main part of Team System consists of modules for Project Management, Work Item management, Source Control, Reporting and Build Management.
Mike gave some great demos of creating user stories and work items in Team System. He also spoke on the different aspects of the Agile Methodology and how Agile and Scrum make the customer a functional member of the team.
All in all, it was an informative presentation.
Great XAML Tool – XamlPadX
XAML stands for Extensible Application Markup Language and is used extensively with Window Presentation Foundation (WPF) and Windows Workflow Foundation (WF). Lester Lobo has created a great tool for previewing XAML code called XamlPadX. I have not played with it too much, but what I have seen so far I like. If you are working with XAML and don’t have the money to spend on Expression Blend, I recommend giving this tool a try.
It is easy to install. Simply take some XAML code and paste it in the application. You get immediate feedback. Very nice.












