384

I was recently working with a DateTime object, and wrote something like this:

DateTime dt = DateTime.Now;
dt.AddDays(1);
return dt; // still today's date! WTF?

The intellisense documentation for AddDays() says it adds a day to the date, which it doesn't - it actually returns a date with a day added to it, so you have to write it like:

DateTime dt = DateTime.Now;
dt = dt.AddDays(1);
return dt; // tomorrow's date

This one has bitten me a number of times before, so I thought it would be useful to catalog the worst C# gotchas.

15
  • 158
    return DateTime.Now.AddDays(1);
    – crashmstr
    Oct 27, 2008 at 19:38
  • 24
    AFAIK, the built in value types are all immutable, at least in that any method included with the type returns a new item rather than modifying the existing item. At least, I can't think of one off the top of my head that doesn't do this: all nice and consistent. Oct 27, 2008 at 19:39
  • 6
    Mutable value type: System.Collections.Generics.List.Enumerator :( (And yes, you can see it behaving oddly if you try hard enough.)
    – Jon Skeet
    Oct 27, 2008 at 19:48
  • 14
    The intellisense gives you all the info you need. It says it returns a DateTime object. If it just altered the one you passed in, it would be a void method.
    – John Kraft
    Oct 27, 2008 at 21:50
  • 22
    Not necessarily: StringBuilder.Append(...) returns "this" for example. That's quite common in fluent interfaces.
    – Jon Skeet
    Oct 27, 2008 at 22:49

61 Answers 61

10
TextInfo textInfo = Thread.CurrentThread.CurrentCulture.TextInfo;

textInfo.ToTitleCase("hello world!"); //Returns "Hello World!"
textInfo.ToTitleCase("hElLo WoRld!"); //Returns "Hello World!"
textInfo.ToTitleCase("Hello World!"); //Returns "Hello World!"
textInfo.ToTitleCase("HELLO WORLD!"); //Returns "HELLO WORLD!"

Yes, this behavior is documented, but that certainly doesn't make it right.

2
  • 7
    I disagree - when a word is in all caps, it can have special meaning that you don't want to mess up with Title Case, e.g. "president of the USA" -> "President Of The USA", not "President Of The Usa".
    – Shaul Behr
    May 5, 2010 at 12:56
  • 6
    @Shaul: In which case, they should specify this as a parameter to avoid confusion, because I've never met anyone who expected this behaviour ahead of time - which makes this a gotcha! May 5, 2010 at 13:18
9

MemoryStream.GetBuffer() vs MemoryStream.ToArray(). The former returns the whole buffer, the latter just the used portion. Yuck.

2
  • Yeah, streams can bite you if you're unaware. I used to have a really bad habit of not remembering to close them. Dec 9, 2008 at 0:26
  • 3
    @MusiGenesis, use using(Stream stream = new ...) { } .
    – tuinstoel
    Mar 12, 2009 at 21:16
8

There is a whole book on .NET Gotchas

My favourite is the one where you create a class in C#, inherit it to VB and then attempt to re-inherit back to C# and it doesnt work. ARGGH

4
  • I guess this is purely Visual Studio weirdness. Jul 8, 2009 at 11:17
  • That's pretty funny.. Anton is probably right.
    – Big Endian
    Apr 7, 2010 at 20:49
  • 2
    I dont find that a gotcha but a useful feature!
    – nawfal
    Apr 10, 2013 at 12:16
  • I think of this as translating English to French then back to English. You often don't end up with exactly what you started with. Jan 8, 2014 at 17:20
8

Dictionary<,>: "The order in which the items are returned is undefined". This is horrible, because it can bite you sometimes, but work others, and if you've just blindly assumed that Dictionary is going to play nice ("why shouldn't it? I thought, List does"), you really have to have your nose in it before you finally start to question your assumption.

(Similar question here.)

7
  • Uh, List<T> does play nice, right? Right? Coz I need to rewrite some stuff if it doesn't. Jun 27, 2009 at 1:29
  • 11
    Of course List<T> plays nice. And use SortedDictionary<T> if the order of items matters to you. Aug 22, 2009 at 20:52
  • 1
    @ck, do you have a link for that? Lot's of people are going to be surprised, I believe...
    – Benjol
    Oct 19, 2009 at 5:32
  • 3
    @ck: Wrong. List<T>.GetEnumerator does preserve order.
    – SLaks
    Aug 19, 2010 at 17:49
  • 1
    I think @ck is suggesting that there are no guarantees implied in the contract that the enumeration will happen in order.
    – user1228
    Aug 20, 2010 at 14:35
8

Static constructors are executed under lock. As a result, calling threading code from static constructor might result in deadlock. Here is an example that demonstrates it:

using System.Threading;
class Blah
{
    static void Main() { /* Won’t run because the static constructor deadlocks. */ }

    static Blah()
    {
        Thread thread = new Thread(ThreadBody);
        thread.Start();
        thread.Join();
    }

    static void ThreadBody() { }
}
7

The DesignMode property in all UserControls does not actually tell you if you are in design mode.

7

The base keyword doesn't work as expected when evaluated in a debugging environment: the method call still uses virtual dispatch.

This wasted a lot of my time when I stumbled across it and I thought I'd encountered some kind of rift in the CLR's space-time, but I then realized it's a known (and even somewhat intentional) bug:

http://blogs.msdn.com/jmstall/archive/2006/06/29/funceval-does-virtual-dispatch.aspx

6

If you're coding for MOSS and you get a site reference this way:

SPSite oSiteCollection = SPContext.Current.Site;

and later in your code you say:

oSiteCollection.Dispose();

From MSDN:

If you create an SPSite object, you can use the Dispose method to close the object. However, if you have a reference to a shared resource, such as when the object is provided by the GetContextSite method or Site property (for example, SPContext.Current.Site), do not use the Dispose method to close the object, but instead allow Windows SharePoint Services or your portal application to manage the object. For more information about object disposal, see Best Practices: Using Disposable Windows SharePoint Services Objects.

This happens to every MOSS programmer and some point.

2
  • So what happens when you dispose it. You kill the entire site? Jan 3, 2012 at 18:40
  • You lose the reference to the site
    – cciotti
    Jan 25, 2012 at 15:27
6

ASP.NET:

If you are using Linq-To-SQL, you call SubmitChanges() on the data context and it throws an exception (e.g. duplicate key or other constraint violation), the offending object values remain in your memory while you are debugging, and will be resubmitted every time you subsequently call SubmitChanges().

Now here's the real kicker: the bad values will remain in memory even if you push the "stop" button in your IDE and restart! I don't understand why anyone thought this was a good idea - but that little ASP.NET icon that pops up in your system tray stays running, and it appears to save your object cache. If you want to flush your memory space, you have to right-click that icon and forcibly shut it down! GOTCHA!

3
  • Surely you mean pause, not stop.
    – Amy B
    Oct 2, 2009 at 5:48
  • David - no, I meant what I said. Even if you push "Stop", the little ASP.NET icon keeps on running in your taskbar. That's why it's a gotcha!
    – Shaul Behr
    Oct 11, 2009 at 13:30
  • 1
    +1 because of the first part, no independent knowledge of the kicker.
    – Maslow
    Oct 28, 2009 at 20:46
5

I frequently have to remind myself that DateTime is a value type, not a ref type. Just seems too weird to me, especially considering the variety of constructors for it.

3
  • 2
    I constantly type lowercase datetime all the time... luckily intellisense fix it for me :-)
    – chakrit
    Oct 27, 2008 at 23:57
  • 4
    Why should this matter? DateTime is immutable anyway and I can't see a situation where you actually need to know if it is a reference type or not. Jul 9, 2010 at 16:45
  • Yes, needs reminding. The most frequent annoyance I've had related to this is that the legacy application I maintain has DateTimes right left and center, and they may or may not unset, uninitialized, valid, etc, and of course I want to see if they are "null", which of course in the DB they frequently are,but can't be in the code. So they have to be DateTime.MinValue or some such magic number or other Kludge, and I have to make sure they are if they have not been absolutely & for sure set to something at least plausible. Aug 4, 2016 at 16:46
5

My worst one so far I just figured out today... If you override object.Equals(object obj), you can wind up discovering that:

((MyObject)obj).Equals(this);

does not behave the same as:

((MyObject)obj) == this;

One will call your overriden function, the other will NOT.

6
  • I used to work with some ex-Java guys who loved to override anything they could get their hands on, and they were constantly screwing each other up with this one. I always used ==, so nothing they did ever affected me. Jun 27, 2009 at 1:38
  • I thought you could overload the == operator as well...
    – RCIX
    Jun 30, 2009 at 10:06
  • 6
    You can override the == operator, but overriding the .Equals() won't do it for you. So you could hypothetically override both .Equals() and ==, and have them do different things :\
    – GWLlosa
    Jun 30, 2009 at 13:09
  • 5
    You can override Equals and overload ==. The difference is subtle but very important. More info here. stackoverflow.com/questions/1766492/… Dec 7, 2009 at 17:05
  • I seem to remember along time ago that == is the value comparison and the .Equals() is the object comparitor. And also if you override the Equals() you have to override the GetHashCode()...not sure. (I may be wrong in that)
    – JPM
    Aug 17, 2011 at 21:15
5

Oracle parameters have to added in order

This is a major gotcha in the ODP .Net implementation of parameterized queries for Oracle.

When you add parameters to a query, the default behavior is that the parameter names are ignored, and the values are used in the order in which they were added.

The solution is to set the BindByName property of the OracleCommand object to true - it's false by default... which is qualitatively (if not quite quantitatively) something like having a property called DropDatabaseOnQueryExecution with a default value of true.

They call it a feature; I call it a pit in the public domain.

See here for more details.

1
5

For both LINQ-to-SQL and LINQ-to-Entities

return result = from o in table
                where o.column == null
                select o;
//Returns all rows where column is null

int? myNullInt = null;
return result = from o in table
                where o.column == myNullInt
                select o;
//Never returns anything!

There's a bug-report for LINQ-to-Entites here, though they don't seem to check that forum often. Perhaps someone should file one for LINQ-to-SQL as well?

1
5

Check this one out:

class Program
{
    static void Main(string[] args)
    {
        var originalNumbers = new List<int> { 1, 2, 3, 4, 5, 6 };

        var list = new List<int>(originalNumbers);
        var collection = new Collection<int>(originalNumbers);

        originalNumbers.RemoveAt(0);

        DisplayItems(list, "List items: ");
        DisplayItems(collection, "Collection items: ");

        Console.ReadLine();
    }

    private static void DisplayItems(IEnumerable<int> items, string title)
    {
        Console.WriteLine(title);
        foreach (var item in items)
            Console.Write(item);
        Console.WriteLine();
    }
}

And output is:

List items: 123456
Collection items: 23456

Collection constructor that accepts IList creates a wrapper around original List, while List constructor creates a new List and copies all references from original to the new List.

See more here: http://blog.roboblob.com/2012/09/19/dot-net-gotcha-nr1-list-versus-collection-constructor/

1
  • Oh my GOD.. thats terrible from BCL
    – nawfal
    Apr 10, 2013 at 12:45
5
enum Seasons
{
    Spring = 1, Summer = 2, Automn = 3, Winter = 4
}

public string HowYouFeelAbout(Seasons season)
{
    switch (season)
    {
        case Seasons.Spring:
            return "Nice.";
        case Seasons.Summer:
            return "Hot.";
        case Seasons.Automn:
            return "Cool.";
        case Seasons.Winter:
            return "Chilly.";
    }
}

Error?
not all code paths return a value ...
are you kidding me? I bet all code paths do return a value because every Seasons member is mentioned here. It should have been checking all enum members and if a member was absent in switch cases then such error would be meaningful, but now I should add a Default case which is redundant and never gets reached by code.

EDIT :
after more research on this Gotcha I came to Eric Lippert's nice written and useful post but it is still kind of weird. Do you agree?

1
  • 2
    The default case will be hit by this code HowYouFeel(42);. Yes there is not enum for 42, but it is still valid. .NET does not constrain enum types to the defined values, and value from the base type of the enum (in this case integer) can be passed. Apr 9, 2014 at 18:59
4

The recursive property gotcha

Not specific to C#, I think, and I'm sure I've seen it mentioned elsewhere on SO (this is the question that reminded me of it)

It can happen two ways, but the end result is the same:

Forgetting to reference base. when overriding a property:

 public override bool IsRecursive
 {
     get { return IsRecursive; }
     set { IsRecursive = value; }
 }

Changing from auto- to backed- properties, but not quite going all the way:

public bool IsRecursive
{
    get { return IsRecursive; }
    set { IsRecursive = value; }
}
2
  • 2
    Not really a gotcha, just careless coding.
    – Shaul Behr
    Sep 2, 2010 at 13:06
  • 1
    Is there a question for that? :)
    – Benjol
    Sep 3, 2010 at 4:49
4

VisibleChanged is not usually called when Visible changes.

1
  • 1
    It seems a more fundamental problem is that "Visible" has different meanings in its getter and setter. The "Visible" property should indicate whether the control should 'try' to show itself, and a separate "CanBeSeen" property should be the 'and' if a control's own "visible" property and its parent's "CanBeSeen".
    – supercat
    Nov 19, 2010 at 0:16
3

Linq-To-Sql and the database/local code ambiguity

Sometimes Linq just can't work out whether a certain method is meant to be executed on the DB or in local code.

See here and here for the problem statement and the solution.

1
3

The worst thing it happen to me was the webBrowser documentText issue:

Link

the AllowNavigation solutions works in Windows forms...

but in compact framework the property doesn't exists...

...so far the only workaround I found was to rebuild the browser control:

http://social.msdn.microsoft.com/Forums/it-IT/netfxcompact/thread/5637037f-96fa-48e7-8ddb-6d4b1e9d7db9

But doing so, you need to handle the browser history at hands ... :P

2

LINQ to SQL and One-To-Many Relationships

This is a lovely one that has bitten me a couple times, and MS left it to one of their own developers to put it in her blog. I can't put it any better than she did, so take a look there.

2

Related object and foreign key out of sync

Microsoft have admitted to this bug.

I have a class Thing, which has a FK to Category. Category does not have a defined relationship to Thing, so as not to pollute the interface.

var thing = CreateThing(); // does stuff to create a thing
var category = GetCategoryByID(123); // loads the Category with ID 123
thing.Category = category;
Console.WriteLine("Category ID: {0}", thing.CategoryID); 

Output:

Category ID: 0

Similarly:

var thing = CreateThing();
thing.CategoryID = 123;
Console.WriteLine("Category name: {0}", order.Category.Name);

throws a NullReferenceException. Related object Category does not load the Category record with ID 123.

After you submit changes to the DB, though, these values do get synched. But before you visit the DB, the FK value and related object function practically independently!

(Interestingly, the failure to synch the FK value with the related object only seems to happen when there is no child relationship defined, i.e. Category has no "Things" property. But the "load on demand" when you just set the FK value NEVER works.)

GOTCHA!

2

I always thought value types were always on stack and reference types on heap.

Well it is not so. When i saw this question recently on SO (and arguably answered incorrectly) i came to know its not the case.

As Jon Skeet answered (giving a reference to Eric Lippert's Blog post ) its a Myth.

Considerably Important Links:

The truth about Value Types

References are not aAddress

The Stack is an Implementation Detail Part 1

The Stack is an Implementation Detail Part 2

1
  • But how is this important when coding? Memory is managed by the framework. Most of the time, you don't have to care. Oct 21, 2013 at 6:08
1

LinqToSQL and the empty set aggregate

See this question.

If you have a LinqToSql query on which you are running an aggregate - if your resultset is empty, Linq can't work out what the data type is, even though it's been declared.

e.g. Suppose you have a table Claim with a field Amount, which in LinqToSql is of type decimal.

var sum = Claims.Where(c => c.ID < 0).Sum(c => c.Amount);

Obviously no claims have an ID less than zero, so you'd expect to see sum = null, right? Wrong! You get an InvalidOperationException, because the SQL query underlying the Linq query doesn't have a data type. You have to tell Linq explicitly that it's a decimal! Thus:

var sum = Claims.Where(c => c.ID < 0).Sum(c => (decimal?)c.Amount);

This is really dumb and IMO a design bug on Microsoft's part.

GOTCHA!

4
  • 3
    No, this is just you being silly. How is .Sum() supposed to return null when you’re using decimal as the static type?
    – Timwi
    Jan 28, 2011 at 23:06
  • @Timwi I would expect it to return 0, to be quite honest. If I'm not mistaken, it returns 0 for in-memory LINQ queries. Plus, it makes sense logically
    – Rob
    Feb 1, 2014 at 23:07
  • @Rob: It does for Sum, yeah — I grant you that — but none of the other aggregate functions (Average, Min and Max).
    – Timwi
    Feb 2, 2014 at 5:15
  • Actually the issue I have with this answer is that it misdiagnoses the problem and misphrases the solution. The problem is not that “the SQL query doesn’t have a data type”, and the solution is not to “tell Linq that it’s a decimal”. The problem is that the SQL query returns null and the solution is to tell Linq to use a nullable type.
    – Timwi
    Feb 2, 2014 at 5:18
1
mystring.Replace("x","y")

While it looks like it should do the replacement on the string it's being invoked on it actually returns a new string with the replacements made without changing the string it's invoked on. You need to remember that strings are immutable.

3
  • 9
    It's immutable; myString is not changed, it returns a new string where 'x' has been replaced by 'y'. Oct 28, 2008 at 9:11
  • 6
    A good convention (unfortunately not used much in .net) is to use two patterns: "string GetReplaced()" for a call that returns a copy and "void Replace()" for methods that alter the original object. The distinct behaviours/usages are then rather difficult to mix up. Jan 31, 2010 at 16:40
  • Ditto? What do you mean? (I know you mean that .Replace returns the modified string, but does not change mystring. You really should edit your answer so that it stands alone).
    – aaaa bbbb
    Oct 7, 2010 at 16:14
1

The following will not catch the exception in .Net. Instead it results in a StackOverflow exception.

private void button1_Click( object sender, EventArgs e ) {
    try {
        CallMe(234);
    } catch (Exception ex) {
        label1.Text = ex.Message.ToString();
    }
}
private void CallMe( Int32 x ) {
    CallMe(x);
}

For the commenters (and downvotes):
It would be extremely rare for a stack overflow to be this obvious. However, if one occurs you aren't going to catch the exception and will likely spend several hours trying to hunt down exactly where the problem is. It can be compounded if the SO occurs in little used logic paths, especially on a web app where you might not know the exact conditions that kicked off the issue.

This is the exact same situation as the accepted answer to this question (https://stackoverflow.com/a/241194/2424). The property getter on that answer is essentially doing the exact same thing as the above code and crashing with no stack trace.

2
  • 9
    Once the stack overflows, no more code can execute, including the exception handler. I'm not sure this is really a gotcha, but I guess it could be confusing if you weren't used to the idea.
    – Chris
    Oct 8, 2009 at 2:06
  • 13
    This is just bad code, not a gotcha.
    – Shaul Behr
    Jan 31, 2010 at 16:04
1

Sometimes the line numbers in the stack trace do not match the line numbers in the source code. This might happen due to inlining of simple(single-line) functions for optimization. This is a serious source of confusion for people debugging using logs.

Edit: Example: Sometimes you see a null reference exception in the stack trace where it points to a line of code with absolutely no chance of null reference exception, like a simple integer assignment.

1

Not the worst, but one that hasn't been brought up yet. Factory methods passed as arguments to System.Collections.Concurrent methods can be called multiple times even if only one return value is ever used. Considering how strongly .NET tries to protect you from spurious wake-up in threading primitives this can come as a surprise.

using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ValueFactoryBehavingBadlyExample
{
    class Program
    {
        static ConcurrentDictionary<int, int> m_Dict = new ConcurrentDictionary<int, int>();
        static ManualResetEventSlim m_MRES = new ManualResetEventSlim(false);
        static void Main(string[] args)
        {
            for (int i = 0; i < 8; ++i)
            {
                Task.Factory.StartNew(ThreadGate, TaskCreationOptions.LongRunning);
            }
            Thread.Sleep(1000);
            m_MRES.Set();
            Thread.Sleep(1000);
            Console.WriteLine("Dictionary Size: " + m_Dict.Count);
            Console.Read();
        }

        static void ThreadGate()
        {
            m_MRES.Wait();
            int value = m_Dict.GetOrAdd(0, ValueFactory);
        }

        static int ValueFactory(int key)
        {
            Thread.Sleep(1000);
            Console.WriteLine("Value Factory Called");
            return key;
        }
    }
}

(Possible) Output:

Value Factory Called
Value Factory Called
Value Factory Called
Value Factory Called
Dictionary Size: 0
Value Factory Called
Value Factory Called
Value Factory Called
Value Factory Called
1

Passing a capacity to List<int> instead of using the collection initializer.

var thisOnePasses = new List<int> {2}; // collection initializer
var thisOneFails = new List<int> (2);  // oops, use capacity by mistake #gotcha#

thisOnePasses.Count.Should().Be(1);
thisOnePasses.First().Should().Be(2);

thisOneFails.Count.Should().Be(1);     // it's zero
thisOneFails.First().Should().Be(2);   // Sequence contains no elements...
4
  • Your statements regarding thisOneFails are incorrect. Count will be 0, and thus .First() will fail. (As a side note, they also don't showcase the behavior mentioned at the beginning of your post)
    – Michael
    Jul 23, 2014 at 13:53
  • thisOneFails is meant to fail
    – SkeetJon
    Jul 24, 2014 at 11:52
  • I apologize. I found the layout of the example awkward: thisOneFails is failing in 2 different places (.Be(1) in the first statement and .First() in the second statement).
    – Michael
    Jul 24, 2014 at 14:25
  • ty for taking the time to reply :)
    – SkeetJon
    Jul 24, 2014 at 18:45
0

LinqToSql batches get slower with the square of the batch size

Here's the question (and answer) where I explored this problem.

In a nutshell, if you try to build up too many objects in memory before calling DataContext.SubmitChanges(), you start experiencing sluggishness at a geometric rate. I have not confirmed 100% that this is the case, but it appears to me that the call to DataContext.GetChangeSet() causes the data context to perform an equivalence evaluation (.Equals()) on every single combination of 2 items in the change set, probably to make sure it's not double-inserting or causing other concurrency issues. Problem is that if you have very large batches, the number of comparisons increases proportionately with the square of n, i.e. (n^2+n)/2. 1,000 items in memory means over 500,000 comparisons... and that can take a heckuva long time.

To avoid this, you have to ensure that for any batches where you anticipate large numbers of items, you do the whole thing within transaction boundaries, saving each individual item as it is created, rather than in one big save at the end.

0

Linq2SQL: The mapping of interface member [...] is not supported.

If you do a Linq2Sql query on an object that implements an interface, you get a very odd behavior. Let's say you have a class MyClass that implements an interface IHasDescription, thus:

public interface IHasDescription {
  string Description { get; set; }
}

public partial class MyClass : IHasDescription { }

(The other half of MyClass is a Linq2Sql generated class, including the property Description.)

Now you write some code (usually this happens in a generic method):

public static T GetByDescription<T>(System.Data.Linq.Table<T> table, string desc) 
  where T : class, IHasDescription {
  return table.Where(t => t.Description == desc).FirstOrDefault();
}

Compiles fine - but you get a runtime error:

NotSupportedException: The mapping of interface member IHasDescription.Description is not supported.

Now whaddaya do about that? Well, it's obvious really: just change your == to .Equals(), thus:

return table.Where(t => t.Description.Equals(desc)).FirstOrDefault();

And everything works fine now!

See here.

Not the answer you're looking for? Browse other questions tagged or ask your own question.