Find me @

Thursday, April 7, 2011

C# tips in a 140 characters or less

Tanzim Saqib had a couple of really nice C# tip posts.

http://tanzimsaqib.com/blog/61/10-c-tips-in-140-characters/
http://tanzimsaqib.com/blog/63/10-c-tips-in-140-characters-part-2/

Summary
Tip 1: double’s internal representation is base 2 and native to the processor, decimal’s base 10, which is 10 times slower than double
Tip 2: double is sufficient for most scientific calculations, whereas decimal is more appropriate for financial.
Tip 3: dont digest, catch & throw that arithmetic overflow: var min = int.MinValue; checked { –min; }
Tip 4: unlike const, readonly objects you can assign in two places: declaration time as well as inside the constructor
Tip 5: you do not need to upcast Animal = (Animal)tiger, but downcast explicitly: Animal animal = tiger; tiger = (Tiger)animal;
Tip 6: how do you make internal members visible? adding this: [assembly: InternalsVisibleTo ("Ally")]
Tip 7: you can extend another interface with the same method signatures: ICredit : IDebit
Tip 8: to implement the same methods of extended interfaces, do it explicitly: ICredit.Charge(decimal d) and IDebit.Charge(decimal d)
Tip 9: you can add implementation specific method body without virtual-override, using new: public new int GetHashCode()
Tip 10: use default(T) for generic type initialization and comparison for you do not know if it is going to be reference/value typesTip 11: In C# 4.0 you are no longer limited to 4 parameters max in Func, 16 it is. Same goes for Action.
Tip 12: From CLR PoV, Stack is where local variables and parameters are stored and removed when not referenced anywhere anymore.
Tip 13: From CLR POV,Heap’s where objects reside.As soon as an object is created,allocated in the Heap and returned a reference to it
Tip 14: For 10x better performance in random access I/O than FileStream,new MemoryMappedFile and MemoryMappedViewAccessor is in C#4.0
Tip 15: MemoryMappedFile facilitates shared random file access across the processes. Use MemoryMappedFile.OpenExisting("SharedFile"))
Tip 16: string.IsNullOrWhiteSpace is newly introduced in C# 4.0, added feature is it allows checking WhiteSpace as well.
Tip 17: BitArray is more memory efficient than array/collection of bool, because instead of byte, it stores bit per element.
Tip 18: are two variables pointing to the same object instance? use: object.ReferenceEquals(a, b)
Tip 19: RegexOptions.Compiled compiles exp to in-memory IL & results 30% faster execution but at a cost of one time slow startup time
Tip 20: to avoid the runtime Regex compilation overhead, you can put them all into single assembly by Regex.CompileToAssembly.

No comments:

Post a Comment