Skip to content

Clever Code

Showcase your best code, your most elegant solution, or your most hard fought subtle bug you've found and fixed

This category can be followed from the open social web via the handle clever-code@forum.codeproject.com

361 Topics 3.2k Posts
  • Enumerable.Except

    csharp linq com question
    13
    0 Votes
    13 Posts
    42 Views
    D
    Maybe you should add an extension method named Expect then :D
  • 0 Votes
    9 Posts
    21 Views
    D
    In related news: If you declare a field to be of type object, it can refer to ANY OBJECT! I mean, REALLY ANY OBJECT!!! THIS IS BLOWING MY MIND!!!!!! Off to write an article about the power of object...
  • Call Dispose on anything

    question
    44
    0 Votes
    44 Posts
    133 Views
    D
    I don't think your scenario description quite worked out as you intended. After a little reflection I suppose you forgot to mention that boz extends foo..? supercat9 wrote: the version of class "foo" with which a program was written does not have a method named "bar", but an extension method of that name exists and is used within class "boz". Translation: class foo {} class boz : foo { public void method() { this.bar(); } } We neither know nor care where the extension method, bar, is declared - but it exists and so this builds. supercat9 wrote: Later on, a method named "bar" is added to class "foo". Unless it is rebuilt, class "boz" will use the extension method, but if it is rebuilt it will use the bar() method from class foo. class foo { protected void bar() { drink(6); Thread.Sleep(TimeSpan.FromHours(11)); } //EDIT: Increased sleep interval :D } class boz : foo { public void method() { this.bar(); } } Indeed it does - if and only if boz extends foo. Also, in this particular example, a more appropriate class name might have been booze. ;)
  • Differences between strncpy and strncpy_s

    css help announcement
    2
    0 Votes
    2 Posts
    9 Views
    M
    Tricky, but: std::wstring is your friend. (And worth the extra lines, even if surrounded by spaghetti.) ........................ Life is too shor
  • Differences between vb.net and c#

    csharp question
    22
    0 Votes
    22 Posts
    131 Views
    M
    I didn't think it is a problem. In VB6 you must use the IS operator to check for Nothing values: If Var IS Nothing Then .... And I am almost sure that it was documented and the behavior you mention of comparing 2 variables when some o both are Nothing can give wrong results. Best regards, Mauro H. Leggieri
  • 0 Votes
    4 Posts
    13 Views
    J
    I have a FormatCString(LPCTSTR lpszFmt, ...) that bakes a CString using it's method FormatV(). Don't have to deal with arbitrary upper limits that way. -- Kein Mitleid Für Die Mehrheit
  • A clever backup...

    question career
    4
    0 Votes
    4 Posts
    14 Views
    L
    I've got an even simpler source code backup plan. It's called SVN - Subversion. Perhaps you've heard of it. Get it from here: http://www.open.collab.net/downloads/subversion/[^] Too complicated? Install TortoiseSVN - Context menu goodness. Plus, it has the added benefits of having your friends respect you. Get it here: http://tortoisesvn.tigris.org/[^] I use mine with a 500G Seagate USB drive. That way I am able to schedule a nightly backup while maintaining control over my source code.
  • 0 Votes
    4 Posts
    11 Views
    D
    Actually, I think the line drawing function is working perfectly. The FillRectangle function actually fills a rectangle defined as (top,left,right-1,bottom-1). The MSDN documentation doesnt clearly state that for FillRectangle, but it does for FillRect (and FillRectangle probably just makes a direct call to FillRect ) Check out the docs to FillRect here: http://msdn.microsoft.com/en-us/library/aa932720.aspx The important part being: This function fills the rectangle's left and top borders, but excludes the right and bottom borders. If it makes you feel better, I've been programming for windows SDK since 1987, and I still forget that from time to time. It's annoying. I disagree with Microsoft's decision process on that one. Dan K
  • Subtle bug, VB style

    help csharp database linq
    7
    0 Votes
    7 Posts
    23 Views
    P
    Michael Eber wrote: But VB.NET used on Xml is what sucks I'm not sure XML enters into it. :~
  • 0 Votes
    2 Posts
    9 Views
    B
    The_Mega_ZZTer wrote: Workaround: Fortunately, taking direct control of the serialization process as described here works like a charm, although the output XML has a few too many tags for my liking I am just happy that it works. Hi, The_Mega_ZZTer, I am curious if there is a "missing link" that was supposed to be included here with this statement. I've read your description of bug #1 carefully, and can't seem to infer what the "workaround" would be other than to not call serialization on nested inherited types. thanks for clarifying, best, Bill "Many : not conversant with mathematical studies, imagine that because it [the Analytical Engine] is to give results in numerical notation, its processes must consequently be arithmetical, numerical, rather than algebraical and analytical. This is an error. The engine can arrange and combine numerical quantities as if they were letters or any other general symbols; and it fact it might bring out its results in algebraical notation, were provisions made accordingly." Ada, Countess Lovelace, 1844
  • Comparing apples to oranges, or strings to bools

    question
    4
    0 Votes
    4 Posts
    15 Views
    P
    It sucks that the correct solutions are always rather complex[^] Personally, I love the idea that Raymond spends his nights posting bad regexs to mailing lists under the pseudonym of Jane Smith. He'd be like a super hero, only more nerdy and less useful. [Trevel] | FoldWithUs! | sighist
  • Linq and "select new"

    database csharp linq com debugging
    8
    0 Votes
    8 Posts
    22 Views
    G
    It's called deferred execution :)
  • Is this brilliant, wicked, or horrible?

    hardware data-structures question
    10
    0 Votes
    10 Posts
    24 Views
    S
    peterchen wrote: I'd put the list of enum definitions into a separate file [and #include it multiple times] I sometimes use that technique. It wreaks havoc with some compilers' efforts to optimize #include file performance (e.g. it prevents the use of #pragma once) but it has the advantage of eliminating a lot of annoying semicolons. Both the multi-#include and the multi-line #define approaches have a certain clunkiness to them, but I've not decided which bit of clunkiness I dislike more. BTW, on one project, it was necessary for a somewhat substantial piece of performance-critical code to operate essentially identically on two data structures. The normal approach would have been to have a routine take a pointer to a structure, and then perform all operations using that structure. An alternative approach would have been for the routine to have a static copy of the structure; to update both structures the code could then copy structure #1 into that static copy, operate upon it, and copy it back, then do likewise for structure #2. This would probably have offered better performance than doing all operation using pointers (on the Z80, using 16-bit integers and pointers would have been rather slow): /* foo.i1 = foo.i2 + foo.i3; */ /* About 16+16+8+16 = 56 cycles I think */ ld hl,(foo.i2) ld de,(foo.i3) add hl,de ld (foo.i1),hl /* bar->i1 = bar->i2 + bar->i3 */ /* About 20+14+14+14+14+14+14 = 104 cycles I think */ /* Note I doubt the compiler would produce code this good */ ld iy,(foo) ld a,(iy+.i2) add a,(iy+.i3) ld (iy+.i1),a ld a,(iy+.i2+1) adc a,(iy+.i3+1) ld (iy+.i1),a but the performance overhead for having to do copy the data structure four times for every system event cycle would still have been substantial. Instead, I #included the code for the routine twice, with a few #define macros set differently for each invocation. (BTW, I just realized that since I defined the PLD for memory addressing, I could perhaps have tweaked it so that a 4K slice of address space could point to two different blocks of memory, and then put the data structure there. Water under the bridge now.)
  • Subtle refactoring C# inheritance gotcha

    csharp regex oop code-review
    4
    0 Votes
    4 Posts
    15 Views
    V
    In this case, it made sense to have a different name, but doing that would have made the refactoring much easier. I wish I would have thought of that at the time. ----- In the land of the blind, the one eyed man is king.
  • Beware of macros!

    c++ help
    12
    0 Votes
    12 Posts
    31 Views
    S
    Nemanja Trifunovic wrote: I have yet to see such a case, at least with C++. What would be your preferred way for initializing parallel arrays, or arrays that have to be parallel to enumerations? Abusing the preprocessor won't always allow one to write very nice source code (sometimes it's necessary to throw in garbage identifiers merely to keep the compiler from squawking) but how would you suggest doing something like the following if as much data as possible must be in read-only storage? #include <stdio.h> #define my_list \ X(foo) \ X(bar) \ X(quack) \ X(moo) \ X(meow) \ X(woof) \ X(bah) \ X(oink) \ /* Do-nothing line concatenated into above definition */ /* Define enumerations en_* for each item in my_list */ #define X(y) en_##y, enum {my_list en_COUNT}; #undef X /* Define st[] containing a string for each item in my_list */ #define X(y) #y, const char *st[] = {my_list 0}; #undef X void main(void) { printf("\n%d %s",en_foo,st[en_foo]); printf("\n%d %s",en_moo,st[en_moo]); printf("\n%d %s",en_bah,st[en_bah]); printf("\n"); } One could include the list twice in the source code--once to define enumeration types and once to define the strings--but that would run the risk of having the two copies get out of sync. One could also use some other utility to take a list of names and output C-compilable source to implement it. If sufficient RAM were available, one could generate st at runtime. On the other hand, if the preprocessor can do what needs to be done, why bring in some other tool?
  • Super-lightweight WinForms TabControl

    csharp winforms
    4
    0 Votes
    4 Posts
    14 Views
    W
    Pretty cool, thanks for showing it.
  • Debugging SQL

    database sql-server sysadmin
    15
    0 Votes
    15 Posts
    38 Views
    H
    The big difference here is "Implicite" and "Explicite" Conversion. The first return is an implicite conversion of the arguments. Both values will convert to a number value and compare. The second return is an explicite conversion and the arguments are converted to VARCHAR or NVARCAHR and compared. The third return is explicite but does not care about anything from the second % SIGN on. RedSpear
  • Simulating C++0x literals - with enums!

    question c++ com algorithms discussion
    18
    0 Votes
    18 Posts
    45 Views
    E
    You spelled "bureaucracy" incorrectly.
  • Hard to find bugs

    question
    11
    0 Votes
    11 Posts
    25 Views
    L
    Gary R. Wheeler wrote: wait 20-30 minutes for your listing, and then realize you made a single character mistake on a card. Ah, memories! My first job was similar - except that, from submission of cards (or, more often than not, coding sheets ready to be punched as cards) it could be several days before we got a listing back - by which time desk-checking had often thrown up the errors that needed fixing! Especially annoying when a coding sheet with "WHILE I IS LESS THAN 10" would get punched as "WH1LE 1 15 LE55 THAN IO" Still, it made us better programmers, I'm sure !?!??! ___________________________________________ .\\axxx (That's an 'M')
  • Fun Perl one-liner

    perl tutorial learning
    5
    0 Votes
    5 Posts
    13 Views
    D
    I discovered this while writing some munge code for some scripts I wanted to obfuscate enough to protect them. I started with more code, as the author did. Some of Perl is subtle. This is one case. Going in the opposite direction, from char to hex, is a bit longer. "Coding for fun and profit ... mostly fun"