C# Code Snippets
[edit]
C# Code snippets / C# Examples / C# Samples
A C# code snippet is a brief example of useful C# source code or Visual C# source code. Sometimes called a recipe, a code snippet usually performs a single function. Being mere fragments of C# source code, the snippets often omit the required using statements. C# source code snippets are categorized alphabetically by namespace. Similar to a code gallery, place your fully functional C# methods in our C# source code bank—C# source code respository or C# cookbook—for all to share.
[edit]
Microsoft.Win32 namespace
- Read a Registry key - read a Windows Registry key.
- Write a Registry key - write a Windows Registry key.
[edit]
System namespace
- Calculate Fibonacci number - recursion example calculates Fibonacci number.
- Calculate simple interest - calculate basic principal and interest on a simple loan.
- Calculate simple interest table - calculate basic principal and interest calculations on a simple loan over a period of years.
- Call with variable arguments - use
paramsto implement a method with a variable number of arguments.
- Cast an object to an interface - access interface members as if they were members of the object.
- Catch an
OverflowException- catch the exception caused by numeric overflow.
- Clear array values using
Array.Clear- clear specified array values.
- Clone an array with
Array.Clone- clone an entire array.
- Convert Fahrenheit and Celsius - convert temperatures between two scales.
- Copy an array with
Array.Copy- copy all or part of an array to a second array.
- Copy one array into a second array with
Array.CopyTo- copy an array to an index into a second array using theCopyTomethod of theArrayclass.
- Create a MD5 Hash from a
string- convert astringto a MD5 hash—a 32-character string of hexadecimal numbers.
- Create a multidimensional
Array- create a multidimensionalArrayof a specifiedTypeusingArray.CreateInstance.
- Create and access a pointer array - create a pointer array of
structaddresses and access them (unsafecode).
- Create and access a heterogeneous pointer array - create a pointer array of heterogeneous addresses and access them (
unsafecode).
- Declare a constant - declare constants of all C# types using the
constkeyword.
- Declare a variable - declare variables of all C# types without initializing them.
- Declare a variable and assign a value - declare variables of all C# types without initializing them and assign values to them.
- Declare and initialize a variable - declare and initialize variables of all C# types.
- Declare multiline string literals - declare string literals which span multiple lines.
- Declare simple event - publish and subscribe a basic
event.
- Demonstrate string methods - demonstrate various
stringmethods.
- Format the date and time - display the various date and time formats.
- Get a number from the console - input a string a convert it to a number.
- Get a Type reference - obtain a
Typereference to a given type.
- Get command line arguments - get the command line argument in
Main.
- Get NetBIOS and DNS computer names - get the local computer name.
- Implement
IDisposableinterface - ImplementIDisposableinterface.
- Measure execution time - measure intervals and execution times.
- NightSky screen saver - a great project for beginning C# programmers.
- Overload the plus operator - overload the plus (+) operator to add objects.
- Override
ToStringmethod - override an object's inheritedToStringmethod.
- Pass anonymous delegate - pass an anonymous delegate as an argument.
- Read Console input - read characters or strings from the
Console.
- Reverse order of array elements - put the elements of an array in reverse order.
- Search array with binary search - conduct a binary search on an array.
- Sort array - sort the elements of an array.
System.Exception- various C# exception handling examples.
System.String- various C# string manipulation functions.
System.String—Find string length - determine the length of astring.
- Test for an interface implementation - test an object to determine if it implements a particular interface.
- Use enumerations - illustrates the declaration and use of enumerated types (
enumkeyword).
- Use enumerations as bit flags - illustrates the use of enumerated types (
enumkeyword) as bit flags.
[edit]
System.Collections namespace
- Calculate prime numbers - find primes using a
BitArray.
- Check
ICollection Countproperty - find the number of elements in an array usingICollection.
- Check
ICollection IsSynchronizedproperty - test anICollectionto see if it is synchronized.
- Enumerate an array - enumerate over the elements of a multidimensional array using the
IEnumeratorinterface.
- Set
BitArrayValue - Set the value of an instance of theBitArrayclass.
- Sort an array in reverse order - sort an array into descending order using the
IComparerinterface.
System.Collections.IListinterface - properties and methods.
- Check
IList IsFixedSizeproperty - determine if an array has a fixed size using theIListinterface.- Check
IList IsReadOnlyproperty - determine if an array is read only using theIListinterface.- Check
IList IsSynchronizedproperty - determine if an array is synchronized using theIListinterface.- Clear an array - clear array values using the
Clearmethod of theIListinterface.- Find common array values - find array values contained in a second array using the
Containsmethod of theIListinterface.- Iterate over an array using
IListinterface - iterate through array values using theCountproperty of theIListinterface.
[edit]
System.Collections.Generic namespace
- Create an indexer property - access a class like an array with an indexer.
[edit]
System.Data.SqlClient namespace
- List SQL Server databases - display list of all SQL Server databases.
[edit]
System.DirectoryServices namespace
- Create Group Object - create a Active Directory (AD) Group Object.
[edit]
System.IO namespace
- Clear Internet Explorer cache - delete all Temporary Internet files.
- Create a directory - create (make) a folder (directory) on disk.
- Delete a directory - delete a folder (directory) from disk.
- Get directory creation time - get the creation time of the named directory.
- Get current directory path - get the current directory path as a string.
- List subdirectories - list all of the subdirectories of the current directory.
- Log messages to a file - log messages to a disk file for debugging or other logging purposes.
- Read a disk file - read a disk text file a line at a time.
- Write then read a text file - read and write a text file to disk.
- Test if directory exists - test whether a named folder (directory) exists on disk.
[edit]
System.Management namespace
- Detect CD-ROM Insertion - detect if CD-ROM is inserted into the CD-ROM drive.
- CD-ROM Loaded - detect if a CD is already in the CD-ROM drive.
- Network Drive Free Space - Obtaining the free space of all network drives.
[edit]
System.Media namespace
- Play default Windows sounds - play the standard Windows sounds from your application.
[edit]
System.Net namespace
- HTTP Post - send an HTTP Post and get the response.
System.Net.Mail- SMTP e-Mail functions.
- Send an e-Mail - send out an e-Mail using SMTP.
- Invalid HTTPS certificate - ignore invalid HTTPS certificate (e.g., calling Web services).
- IP Address - get the IP address of the Host PC.
[edit]
System.Reflection namespace
- Display
Assemblyattributes - list all the Assembly attributes in an assembly.- Display type version number - display the version number of a given component.
- List
Assemblyexceptions - list the public exceptions from Assemblies.
[edit]
System.Runtime.InteropServices namespace
- Create a C-style union - use
ExplicitLayoutto layout astructin Visual C#.- Empty the Recycle Bin - empty the Recycle Bin.
- Open/close CD drive tray - open and close the CD drive tray.
[edit]
System.Security.Principal namespace
- Check if principal is Administrator - check if the current user is an Administrator.
[edit]
System.Text.RegularExpressions namespace
- Check if all numeric string - returns
trueif string contains no alphabetic characters.- Check if all upper case string - returns
trueif string contains no lower case characters.- Parse connection string - finds the host name, instance name, and database name in the connection string.
- Strip all HTML tags - removes all HTML tags from the input string.
[edit]
System.Threading namespace
- Check current thread priority - get the
Priorityproperty of the current thread.- Check if current thread is a thread pool thread - test
IsThreadPoolThreadproperty of the current thread.- Check if current thread is alive - test the
IsAliveproperty of the current thread.- Check if current thread is background thread - test the
IsBackgroundproperty of the current thread.- Check the state of the current thread - get the
ThreadStateproperty of the current thread.- Get current thread name - get the
Nameproperty of the current thread.- Set current thread name - set the
Nameproperty of the current thread.- Use the
TimerCallbackdelegate - theTimerCallbackdelegate is used for periodic call backs.
[edit]
System.Windows.Forms namespace
- Pick a color with
ColorDialog- select a color using theColorDialogdialog box.
- Select a file with
OpenFileDialog- pick a file using theOpenFileDialogdialog box.
- Set a control font with
FontDialog- set the font in a control withColorDialog.
- Retrieve the current screen resolution - get the screen resolution using the
SystemInformationclass.
[edit]