25 Things Ive learned about C# in the past 10 years
25 Things Ive learned about C# in the past 10 yearsPhil Denoncourtphil@denoncourtassociates.comhttp://philknows.net1VersatilityDesktops WinFormWPFLinux, Mac, SolarisServersWeb AppsServices (web/native)Embedded SystemsMicro .NET (Netduino, FEZ Domino)Windows PhoneRobotsiPhoneGaming ConsolesXbox 360Wii, Playstation 3 (via Mono)
225 Things I've Learned about C# - Phil Denoncourthttp://mono-project.com2Difference in SpeedC# compiles to bytecodeSo it must be slowBytecode gets compiled to native code upon first usageTakes advantage of features that machines processorMatches C++ in Int math, trig, and I/O.Little slower in floating pointC# benefits from disposing of objects when idlerather than when object is no longer used.http://www.osnews.com/story/5602&page=3325 Things I've Learned about C# - Phil Denoncourt3SpeechBuilt into the framework since 3.0Add reference to System.SpeechRecognitionCommand basedDictationSynthesisRequires SAPIWindows Vista and LaterOffice 2003 and Laterhttp://gotspeech.net
425 Things I've Learned about C# - Phil Denoncourt4Multi-ThreadingIts easy to writeThreadPool.QueueUserWorkItemPLINQBackgroundWorker componentIts hard to debugAdd trace / logging to your codeMake sure your classes are ThreadSafeLock keywordInterlocked classhttp://www.bluebytesoftware.com/blog/
525 Things I've Learned about C# - Phil Denoncourt5Nullable TypesAdded in 3.0. Implemented as a generic classAllows you to consider value types that are nullableAdd ? to end of typeInt?DateTime?String is already a reference type, thus already nullableNull Coalesce operatorSubstitutes a value if the object is nullReally low in operator precedence. Often need parens.http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx
625 Things I've Learned about C# - Phil Denoncourt6Throwing ExceptionsExceptions hold a lot of informationThrowing them is computationally expensiveAvoid using exceptions as logic flowStack trace line numbers are available if PDBs are present with the binariesThere is a difference betweenthrowthrow ex;http://msdn.microsoft.com/en-us/library/5b2yeyab(v=VS.100).aspx725 Things I've Learned about C# - Phil Denoncourt7Checked / VolatilecheckedBy default, overflow checking is disabled in C#Depending on compiler optionsPlacing statements in checked block enables checkingThere is also an unchecked keywordhttp://msdn.microsoft.com/en-us/library/74b4xzyw(v=VS.100).aspxvolatileKeyword that indicates field could be updated by multiple threadsDisables compiler optimizations that assume single threaded accessPlaces a lock statement around access to the fieldhttp://msdn.microsoft.com/en-us/library/x13ttww7(v=VS.100).aspx
825 Things I've Learned about C# - Phil Denoncourt8Extension MethodsAllows you to add new methods to existing classesEven sealed classesCan operate on public membersBut not private membersGood way to add missing functionality to classGood way to make something unmaintainableInternally implemented as a static method passing in the current instance.
http://extensionmethod.net/925 Things I've Learned about C# - Phil Denoncourt9Lazy ObjectsGeneric template that defers initialization until usedSystem.LazyObject will be initialized when the value member is accessed, or ToString() is called.
http://weblogs.asp.net/gunnarpeipman/archive/2009/05/19/net-framework-4-0-using-system-lazy-lt-t-gt.aspx1025 Things I've Learned about C# - Phil Denoncourt10Goes to operatorLambda operator =>Anonymous functionContains codeReturns a delegateUsed extensively in Linq
http://msdn.microsoft.com/en-us/library/bb311046.aspx1125 Things I've Learned about C# - Phil Denoncourt11LinqEliminates a lot of repetitive codingImplemented as extension methods in System.Linq.dllMust reference the assembly, and add a using statement:using System.Linq;Different providers allow access to different types of data by exposing IQueryable interfaceLinq to ObjectsLinq to SQLLinq to EntitiesLinq to Xmlhttp://msdn.microsoft.com/en-us/netframework/aa904594.aspx1225 Things I've Learned about C# - Phil Denoncourt12ThreadStaticNormally static fields exist once per AppDomain[ThreadStatic] static fields exist once per ThreadStatic constructors and initializers still only execute once.So you have to make sure the object is not null before using it
http://blogs.msdn.com/b/jfoscoding/archive/2006/07/18/670497.aspx1325 Things I've Learned about C# - Phil Denoncourt13TypeForwardedToAttributeAllows you to move a class from one assembly to another without breaking callers[assembly:TypeForwardedTo(typeof(classThatWasMoved)]Place this statement in the original assembly, which must reference the new assembly.Used for refactoring types into different assemblies, and not have to rebuild the caller assembly.Namespace and name cant changeCan also redirect entire assembly in .config fileassemblyBinding sectionhttp://msdn.microsoft.com/en-us/library/ms404275.aspx1425 Things I've Learned about C# - Phil Denoncourt14EnumsDont need to be based on intCan be byte,sbyte,short,ushort,int,uint,long, orulong.If you use the FlagsAttribute, you can perform bitwise operationsMeaning that you can store more than one state in an enum variable.
http://dotnetperls.com/enum-flags1525 Things I've Learned about C# - Phil Denoncourt15Using-In addition to allowing shortcuts to namespacesAutomatically disposes objects when scope is outside of the using statement.Object doesnt need to be instantiated in the using statementBut shouldMore than one object can be tracked by a using statementBut they must be of the same type http://msdn.microsoft.com/en-us/library/yh598w02.aspx
1625 Things I've Learned about C# - Phil Denoncourt16ReflectionAllows you to examine metadata about compiled code.Has a reputation for being slowI havent found that to be very trueAllows access to private methods / fields of a classYou can also get the actual IL of the method for reverse engineeringWhich is what Reflector does
http://msdn.microsoft.com/en-us/library/f7ykdhsy(v=VS.100).aspx1725 Things I've Learned about C# - Phil Denoncourt17ConstructorsCan call other constructor methodsAdd :this to call a constructor in the current objectAdd :base to call a constructor in the base object
http://msdn.microsoft.com/en-us/library/ms173115.aspx1825 Things I've Learned about C# - Phil Denoncourt18GenericsAllows you to write code against an abstract typeType ParameterWhen generic is used, a type is specified. Reduces the amount of boxingGenerics can be applied toClassesDelegatesMethodsInterfacesInstead of comparing to null, compare to default(t)http://msdn.microsoft.com/en-us/library/512aeb7t(v=VS.100).aspx
1925 Things I've Learned about C# - Phil Denoncourt19ConstraintsAllows you to constrain what types can be used with a genericCan constrainClasses that implement an interfaceClasses must have a common base classParameterless constructorThat the type is a classThat the type is a structConstraints enforced by the compilerhttp://msdn.microsoft.com/en-us/library/d5x73970.aspx2025 Things I've Learned about C# - Phil Denoncourt20File IOVery easy since .NET 2.0No more worrying about holding onto disposable objectsFile class static methods for CopyingRenamingDeletingChecking existingReading /writing data to a fileEncrypt/Decrypt a filehttp://msdn.microsoft.com/en-us/library/system.io.file.aspxPath class static methods for Assembling a filenameChanging extensionsGetting a truly temporary filenamehttp://msdn.microsoft.com/en-us/library/system.io.path.aspx
2125 Things I've Learned about C# - Phil Denoncourt21GlobalizationMostly done for you.NET 4.0 supports 354 different culturesAllows you to properlyFormat numbersFormat currencyFormat date/timesCompare stringsBy default, the culture of the current thread is used when formatting/comparingGlobalization != Localizationhttp://en.wikibooks.org/wiki/.NET_Development_Foundation/Globalization2225 Things I've Learned about C# - Phil Denoncourt22Write your own codeYou can write code that writes codeEmits C# or VB.NetOr can build an assembly using a compilerCan build the assembly in memoryDoesnt get written to disk.
2325 Things I've Learned about C# - Phil Denoncourt23Create Zip FilesGZipStream class only compresses one fileSystem.IO.PackagingAdd reference to WindowsBaseAdd each file as part of the packageIt will add a [Content_Types].xml file to every zip filePart of the open packaging specification
http://madprops.org/blog/zip-your-streams-with-system-io-packaging/2425 Things I've Learned about C# - Phil Denoncourt24Few little thingsGoto in switch statement>> multiplies by powers of 2,