Should ‘using’ directives be inside or outside the namespace?

I have been running StyleCop over some C# code, and it keeps reporting that my using directives should be inside the namespace. Is there a technical reason for putting the using directives inside instead of outside the namespace? 12 There is actually a (subtle) difference between the two. Imagine you have the following code in … Read more

Difference between decimal, float and double in .NET?

What is the difference between decimal, float and double in .NET? When would someone use one of these? 1 18 float and double are floating binary point types. In other words, they represent a number like this: 10001.10010110011 The binary number and the location of the binary point are both encoded within the value. decimal … Read more

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

How do I convert a string to a byte[] in .NET (C#) without manually specifying a specific encoding? I’m going to encrypt the string. I can encrypt it without converting, but I’d still like to know why encoding comes to play here. Also, why should encoding even be taken into consideration? Can’t I simply get … Read more

Catch multiple exceptions at once?

It is discouraged to simply catch System.Exception. Instead, only the “known” exceptions should be caught. Now, this sometimes leads to unnecessary repetitive code, for example: try { WebId = new Guid(queryString[“web”]); } catch (FormatException) { WebId = Guid.Empty; } catch (OverflowException) { WebId = Guid.Empty; } I wonder: Is there a way to catch both … Read more

Deep cloning objects

I want to do something like: MyObject myObj = GetMyObj(); // Create and fill a new object MyObject newObj = myObj.Clone(); And then make changes to the new object that are not reflected in the original object. I don’t often need this functionality, so when it’s been necessary, I’ve resorted to creating a new object … Read more

How to enumerate an enum

How can you enumerate an enum in C#? E.g. the following code does not compile: public enum Suit { Spades, Hearts, Clubs, Diamonds } public void EnumerateAllSuitsDemoMethod() { foreach (Suit suit in Suit) { DoSomething(suit); } } And it gives the following compile-time error: ‘Suit’ is a ‘type’ but is used like a ‘variable’ It … Read more

Clear controls does not dispose them – what is the risk?

There are multiple threads(a, b, c etc.) about the fact that Clear() ing items in the .NET component containers does not Dispose them(by calling Dispose(true). Most frequently, IMHO, the Clear-ed components are not used anymore in the application, so it needs explicitly be Disposed after Clearing them from the parent containers. Maybe is a good … Read more