Posts Tagged ‘C#’

Just a short thought on Qt

June 19, 2015 Leave a comment

Qt has (sometimes huge) design mistakes in my opinion but it’s far from bad. But try to look up unrelated information about it, and you’ll find the fanboys defending every silly thing about it.

For example, when you design a window in the Qt Designer, it creates an XML file with the .ui extension. That file is then translated to source files. The generated header has code like this:

class Ui_MainForm
    // ... Declarations of widgets and some helper functions.

below it another class is generated in this exact way:

namespace Ui {
    class MainForm: public Ui_MainForm {};
} // namespace Ui

The class in the Ui namespace can then be used as a private member in another header file, which is provided for the programmer to change: (because the code above is auto generated)

class MainForm : public QMainWindow
    // ... some things you add here
    Ui::MainForm ui;

Not one, but more people asked why is there a Ui::MainForm generated, when there is also a Ui_MainForm, which is the exact same thing. They were just curious and asked politely but the fanboys attacked. “It seems to me you do not get what namespaces are” (exact quote).

(This is the end of the post. If you don’t understand why I’m troubled by such reactions you are either not a programmer (it’s normal then, not your fault), or you are smarter than I am and the way Qt does this appears right to you.)

Categories: Rant Tags: , ,

C# – Final conclusion (for now)

January 25, 2012 8 comments

Disclaimer: Not a well thought out post. Just a little summary. And with C# terms here and there.

I don’t want to write as much as I did in my past few posts about programming, so there is not much space for today’s C#. 🙂

My feelings towards C# and .NET are mixed. VS makes me want to play with it more. On the other hand whenever I try out some neat trick I thought up a moment ago and it turns out not to work, because the language or the framework doesn’t let me, I get very disappointed. C# “the right way” requires a lot of typing. Implementing interfaces, even if VS has a feature to automatically add the required functions, feels like I’m repeating the same thing a thousand times. .NET’s use of memory and speed makes me think about users who would be very unhappy with programs written in it. The foreach which would be usable with a built in counter, and if it wouldn’t demand implementing some interface (or the single GetEnumerator function) is killing me, and its almost never the good choice. (Though elegant for sure.) Not knowing what’s going on behind the scene is scary. I have an urge to avoid all the .NET classes written for specific purposes as they tend to have terrible performance. The obsession against pointers forces me to write everything with extra care. Does it need to be “boxed”? If I pass around lists, will they get recreated a lot? Anything that returns collections, enumerators etc. creates new objects, then you throw them out and make your own just to return that, and this could go on for several levels. Pointers need care because they can cause really terrible things, but avoiding pointers give you a whole lot of other problems. And it’s also very difficult to debug.

But then that feeling comes back that I must touch VS again…

Categories: Rant Tags: ,

Are built in C# classes really that great?

January 18, 2012 Leave a comment

Disclaimer: same as before…

UPDATE: There was an error in the test which I explain in the next post.

I have created my own sorted list which implements the same interfaces as SortedList, but it has exactly what I need for a sorted non-binary tree structure. Done a little testing and as it was obvious from the start, my class is faster.

My results:
random insertion and deletion: 1024
ZSortedList: 5ms (+1ms)
SortedList: 4ms

random insertion and deletion: 1024 * 4
ZSortedList: 22ms
SortedList: 23ms (+1ms)

random insertion and deletion: 1024 * 8
ZSortedList: 57ms
SortedList: 77ms  (+20ms)

random insertion and deletion: 1024 * 64
ZSortedList: 3260ms
SortedList: 6184ms  (+2924ms)

random insertion and deletion: 1024 * 100
ZSortedList: 7844ms
SortedList: 15131ms  (+7287ms)

Running conditions:
Both lists start out with a capacity of 1024 * 8 items
When I didn’t set a starting capacity for my own list, it was a bit slower than SortedList with low item count, but once I set the number of items to add to 1024 * 8 or higher, my list suddenly won every test, so I’m guessing this is near the default capacity of a SortedList.

Both lists have KeyValuePair<string,int> items.
This is needed because my list doesn’t have a type for keys, the items hold the keys and it would have been unfair if I had to create KeyValuePairs for my own list but not for the SortedList.

The key used for comparing items was a string in both cases. I passed my own IComparer to both lists to compare them. The key was a random number between 0 and 1000000000 converted to string.

I used a Stopwatch object to measure the time.


My list checks the position, and if it is free, adds the item there. With the original code that I wanted to test, SortedList searched for the position twice, once to see if it can add the item and again to add it for real. In the modified code it only checks once and I have to catch its exceptions when trying to insert to an occupied position, but the results stayed nearly the same.

It is difficult to draw a conclusion. Either the try/catch handling takes as much time as searching for a string position, or there is some strange caching going on in C#. In the latter case I can’t say for sure whether my class is really that fast. I think what really slows down SortedList is not looking for the position at all, but adding the item, that’s why I couldn’t see much time difference in the two test cases. I have no idea what inner data structure it might use, probably some kind of list. My class on the other hand works on the most basic of data structures, an array, using the Array.BinarySearch static function to find the string position, and the Array.Copy when the array needs to be recreated. It’s good to know that C# array handling is working nicely, but I think there might be other strange results if I tried to recreate all the other collection types as well.

Here is the full code before someone says I cheated:

ZSortedList<KeyValuePair<string, int>> l1 =
    new ZSortedList<KeyValuePair<string, int>>(8*1024,new PlainComPair());
SortedList<KeyValuePair<string, int>, int> l2 =
    new SortedList<KeyValuePair<string, int>, int>(8*1024,new ComPair());
Stopwatch watch = new Stopwatch();
Random r = new Random();
string key;
int val;
for (int ix = 0; ix < limit; ++ix)
    key = r.Next(1000000000).ToString();
    val = r.Next(1000000);
    var pos = l1.AddPos(key);
    if (pos != null)
        l1.AddToPos(pos, new KeyValuePair<string, int>(key, val));
while (l1.Count > 0)
long n1 = watch.ElapsedMilliseconds;
for (int ix = 0; ix < limit; ++ix)
    key = r.Next(1000000000).ToString();
    val = r.Next(1000000);
    KeyValuePair<string, int> pair = new KeyValuePair<string, int>(key,val);
//if (!l2.ContainsKey(pair)) // <-- Commented out and added the try/catch block
        l2.Add(pair, val);
    catch (Exception)
while (l2.Count > 0)
long n2 = watch.ElapsedMilliseconds;
Categories: Rant Tags: ,

C# strikes back

January 18, 2012 Leave a comment

Disclaimer: The usual. A post about programming in C#. This entry has some harsh criticism which might offend people. No, it is almost only criticism though it applies to (MS) libraries in general not just .NET.

I’m currently trying to make a class for holding data in a non-binary tree structure.  Although I started this as a continuation of my last uploaded project to see how fast searching can get if I keep the look-up tree in memory (similarly how it is done in zkanji), but creating such a tree is pretty trivial. As I do all this to see what C# and “managed” code can give that C++ couldn’t, I thought I’ll do this class “the right way”. That means I have to make a generic class with generic types for keys and values, but also that many of the tree’s properties have to be accessed through built in interfaces so it uses the full potential of the language.

My first decision was to create a tree class (I call it ZTree, hehe), which was a node itself, and each node of the tree were really different objects of the same class. But then again I guessed this is not the C# way, so the second step was to create a separate ZTree and ZTreeNode. This decision wasn’t simply based on that though. If there is a separate tree class, I can hold some values that influence how the whole tree works without “bloating memory” (my second “favorite” phrase from forums after “strongly typed”.)

I have tweeted yesterday that I wasted time with a blog that only stated the obvious. The writer of that blog not only made a separate class for the nodes, he also made a class for the list of nodes to hold sub-nodes inside the nodes. .NET (and many other libraries) do this. They have a class A, a class B holding many objects of class A, a class C listing class B type objects, a class D that needs a class C for listing class A inside class B etc. (To be fair the iostream and many other IO classes used in C++ work in a similar fashion.) I don’t want to get into a fight with anyone about this. I know this makes sense in a purely philosophical way. In object oriented programming the aim is to make code which has few errors and is easy to change. If someone needs to replace a tiny part of some structure without “breaking code”, they just inherit a class to write their own handling for the specific problem. This all is well, but I often have the feeling library creators overdo it for their own perverse satisfaction. Actually I only wanted to write that my tree class won’t be doing this even if it’s not as nice and elegant, because I prefer practical over elegant.

The ZTreeNode class in the current implementation is derived from the generic SortedList<TKey,TValue> because I wanted to have keys for nodes not just indexes, and the keys must be unique and sorted. (Maybe I should call the main class ZSortedTree with ZSortedTreeNodes?) Each node has a value and holds its own sub-nodes directly without an additional layer of sugar. The reason why someone might want to create a separate class for a node list is probably because they want that list to be enumerable through interfaces and the node should do something else through other interfaces. Of course my code wouldn’t resemble anything in C# if I didn’t have my own enumerable stuff, so I created a few properties (namely to enumerate the values of a node, the nodes of a node by index (via IList) and once again the nodes of a node by key (via IDictionary). This latter part is probably unnecessary but once you start creating properties it’s hard to stop.)

This was a really good experience with C# and I have learned a lot, but the work is far from done. I’ll have to replace the SortedList ancestor with maybe a normal list, or an entirely new type derived from object that holds (gasp) arrays. because though a SortedList might be fast, it wasn’t created with inheritance in mind. (Which is strange when the .NET library is intentionally complex so people can customize everything.)

I made a function called “Add” to add new nodes to a parent node. The function should check whether the key for the new node already exists and if it does, stop right there. The generic SortedList has convenient functions to check for the existence of keys, and it also throws an exception if we try to add something with an existing key. For the purpose of my own “Add” function this could work, but maybe as I mostly code in C++, I feel uncomfortable for having to do things twice or wasting memory. Either looking up things twice or creating an object just to throw it away.

If I check for the existence of a key first, SortedList will have to find the place for the key in order to see whether it exists or not. If the key doesn’t exist and I try to insert a new object, SortedList will have to find the position of the key again for the insertion. On the other hand if I simply add a new object and catch the exception, I have created an object for nothing. This might not be such a serious sin in C# where the GC automatically cleans up spilled stuff, and probably nobody would use this class to try to add thousands of existing keys, I still feel bad about creating and throwing away memory for nothing. It occurred to me just now that if I add a null value there won’t be anything wasted, but I see that the “Add” function of SortedList doesn’t return the index for the added null value. Too bad, I could have used that. This is the feeling I have with .NET a lot. It could be good, but…

My other bad feeling with using a SortedList is its incredible number of functions that operate on keys and values. It takes a lot of work to hide all those so people won’t break the structure of the tree. For example placing a node as a sub-node of itself or a child node would create a closed circle and trees are usually famous for not having those. I’ll have to check, maybe all those functions are harmless and decide after that whether I really want to create my own sorted list because I hate reinventing the wheel. (Why do I make a tree then, right?) UPDATE: turns out I’m just not observant enough. Many functions are provided by the interfaces that SortedList implements without really having an effect on the tree structure.

As the closing words for this long and boring rant, here is the reason why I need a sorted tree: I want to hold words in it for the dictionary! The key of each node will work like the labels in my original tree in zkanji which I explained in this old post, and the values for the nodes will each be lists to indexes of words in the SQL database. For that I first need to finish my generic tree, then inherit a tree from that which can manage the words, insert them in the right position etc. I’m curious whether this will result in less memory consumption compared to holding not just the look-up tree but the whole database in memory like in my C++ code. I’m prejudiced that C# eats memory for breakfast. I’ll see.

Categories: Rant Tags: ,

Small project in C#

January 16, 2012 Leave a comment

Disclaimer: Sometimes I feel like writing about programming. And then I do. If it is not your cup of tea, don’t read this.

In case anyone is interested, I have uploaded the source files of my second “project” I wrote in C# as an exercise. There is no documentation for it and I have no idea what files make up a C# project, so I just packed everything in a ZIP file. To compile you will probably have to change a few paths, but apart from that nothing is necessary. Just download this SQLite port for C#, add the System.Data.SQLite DLL from it to the project and it should compile. I used Visual Studio 2010 express and it needs at least .NET 3.5 or maybe 4.0(?). Don’t expect anything serious, this is something I wrote in 2 days.

How to use (once it compiled):

  1. Download JMDict_e.gz and unpack the file as JMDict_e.xml to the “debug” or “release” folders created automatically for the project. (In other words, the data must be in the executable’s folder.)
  2. The data file is called JMDict_e without an extension, remember to add .xml!
  3. Run the program. This will create a database SQLite can use. (It will throw an exception when it’s done, don’t worry about it.)
  4. Close the program and run it again. You can browse the dictionary.

I have used many C# features that are not present in C++ and it’s possible that an experienced C# programmer would never do it like how I did. Still I’m proud of it as I have used some “advanced” programming features (i.e. reflection) after only spending a few days with the language. For example to describe table columns to my little SQLite wrapper, you just have to create a class containing some fields… Yes, it is nothing serious. Sorry for bringing it up… I have only uploaded it because I didn’t just want to delete the code after spending the whole weekend writing it.

My conclusion: (In the now traditional list format)

  1. I could learn this language to some extent if I spent a little more time on it.
  2. MS documentation sucks. It tells you how to use A to achieve B without explaining what A or B is. Good luck finding out information about those.
  3. MS documentation sucks.
  4. C# has a few intriguing features I have no idea how to use, but I suspect some great secrets are waiting to be discovered.
  5. I still don’t get it why anyone in their right mind would use interfaces apart from the compulsory built in types. Abstract classes always give greater freedom with additional features.
  6. It is clear why static cannot be virtual in C++, but in C# the class types are practically objects themselves (when using reflection) and functions can be easily invoked on them. Static virtual functions would have made my life so much easier…
  7. The compiler and program make up all kind of new types as they execute, which is very confusing for a beginner.
  8. No matter whether it is the built in database with ADO.NET or SQLite, both are very slow to make a dictionary like zkanji which has to look up tens of thousands of words each second. I couldn’t achieve more than 2-3000. Scrolling the dictionary had acceptable speed, but searching while typing simply didn’t work. I will try to rewrite the whole program, either by keeping some look-up data in memory all the time if it’s possible, or creating my own data handling classes, like I did in zkanji. (I could probably port the dictionary browsing code from C++ in a few hours but then I wouldn’t learn anything.)
  9. There is no point comparing Visual Studio with Rad Studio. Both are great in some things, terrible in others. (Is there a way to look up the result of function calls in the debugger in VS without having to step into them?)
  10. Intentionally trying to write complex code just to learn something is fun. (Only depends on your idea of fun, really.)
  11. I wish I had someone to ask about C# while coding. I have no idea if I did things the orthodox way or my solutions were so crazy no wonder it was a pain to make them work.
  12. You can see the keywords like “strongly typed” a lot while learning C#, because the documentation writers and forum posters are all proudly using them. I don’t say it’s bad or good or anything, C++ is “strongly typed” too after all, but they all sound like some ad slogan to me.
  13. I don’t hate C# more than C++, even if someone might think so from reading my blog. I just stopped complaining about C++ long ago.

I could probably make up more to write if I thought about it, but I’m tired and the only real conclusion I’m serious about is that I’m not satisfied with my own performance yet. (I bet I’ll get a lot of spam for this.) I think I haven’t used most of the central C# features, or not how they were intended to be used, and instead used others that people would only try as their last resort. Or maybe not, but there is no way for me to find out.

Categories: Other projects, Rant Tags: ,

Visual Studio and C# Impressions

January 11, 2012 2 comments

Disclaimer: Only programmers will be able to appreciate this entry. And even that’s not certain.

I wrote a much longer entry yesterday but after some thought I realized that nobody would read it, and there was no point to share all that, because pure C# programmers wouldn’t learn anything new and pure C++ programmers wouldn’t get it.

Last year just before Christmas I installed the free Visual Studio 2010 Express on my machine, namely its C# and C++ compilers. I was curious about VS, as I haven’t seen it for some time and never tried C# before. I can confirm that it’s very easy to start with that language (at least if someone has 12 years experience with C++), because I finished my very first Windows forms application with it, a simple clone of minesweeper, with dynamically created cells and all, in one and a half hours after first starting up VS, without knowing anything about C#. (This time includes reading documentation and hunting for information online, the actual writing didn’t take longer than half an hour at most.)

Of course this didn’t make me an experienced C# programmer, and I didn’t spend enough time getting used to the IDE of VS either. VS has some glitches that became apparent from a little  use though. For example compiling in the C# IDE is invoked with the F6 key, while in the C++ IDE it’s F7. I would expect the same keys to execute the same basic functionality in both interfaces. It is a single company after all. The other glitch was with the compiler paths. I can’t remember whether I have changed the install path for the compilers, but the C++ IDE couldn’t find the compiler’s “Cl.exe”. I found nothing about it after searching online, but then checked the compiler macros, namely the macros used for the program paths, and noticed an error in one of them. There was no way to change that path from the program itself, but fortunately the paths are not encoded, and a little work with regedit helped me find and correct the error. (Yep, MS still hasn’t learned not to hard code paths in its programs or installers.)

Every program has bugs, and I haven’t spent enough time with VS to discover more, so I’ll leave it at that. The only thing I could do in such a short time was to compare some features of VS with the ones in Rad Studio that I’m using to write zkanji. The form designer of VS is an obvious rip off of Rad Studio’s (or rather the original in Delphi from 1995), which is not a problem in itself, though I found the designer in VS a bit unresponsive and slow when moving controls around a form. I found some inconveniences as well that work so nicely in Rad Studio but not in Visual Studio for some reason. The most obvious is how some controls can only be moved in VS by grabbing a small icon at the top border of a control. I might be a bit unfair here as I’m used to RS too much, but its solutions feel much better to use.

On the other hand the text editor part of VS is light years ahead of the one in RS. It’s faster, and the IntelliSense, which helps writing the code works much better than the CodeInsight of RS. They both suggest possible names for variables and their functions, the functions’ arguments etc. but VS makes it look like it’s easy, while RS is clearly struggling each time. (This may be due to the huge code of zkanji, but I can’t be sure until I have written something just as big in VS.) The way how VS completes code and formats the lines, so brackets always start at a new line and all those little things are done much better than in RS as well.

Up till now was my impression about Visual Studio, so let me write about C# and .NET as well. I have 12 years of C++ experience, so I can’t help but to compare the two languages. It’s clear, that C# was derived from C++, because they share many keywords and the way loops for example work is very similar as well. Of course C# has foreach and an sql like expression to collect items from lists and arrays, and C++ only gained some of the functionality with C++11 (and we have to see until every compiler starts to support it.) If someone knows how to use C++, C# won’t be difficult at all. Starting with it is just a matter of minutes, not even hours. They usually say that this is one of the strong points of the C# language (I heard something similar about Java a decade ago). In my opinion this is not necessarily a good thing, but not bad in itself either. After spending days reading the C# language reference I think that it is a language that looks simple, and it is easy to start with some simple programs, but using something that has simple rules can get very complicated with time.

I never liked garbage collection so I’m prejudiced, and because of that I’d rather not get into this part of the language, just mention what I think about languages with no pointers in general. When we start hiding pointers the language loses features. Even in C++ you could write and use classes that hide the pointers, and it is probably better for safety as well, but at least they don’t take away the tools. This doesn’t have much to do with C# so I stop here. I’d rather write about my first impressions, if that was the title of this entry.

As I was writing, it’s true that C# seems much easier to learn than C++. The biggest headache I had in C# was with class inheritance and mainly virtual functions and properties. I find it odd and a bad design that you can’t change the visibility of C# class members. Why is that, that when a virtual property was declared protected in a base class, it can’t be made public in a derived class? Or what is even more problematic, if it was public, it can’t be made protected? I found an answer on a site where someone asked the same question. One of the first people to answer said that it would be against the principles of Object Oriented Programming, though I have never heard of such principle. If you know about it, please tell.

Imagine the situation that you create a new listview control, that can only show its items as rows in a detailed list. (Listview is the control that lists files in the right part of Explorer. It can show the files as icons, or it can show details etc.) In C# it is impossible to change the visibility of the public virtual “View” property to protected. With a little research I found the solution, hiding the property with a new one with the same name, that only has a public getter function, while the setter is either private or doesn’t exist. It is strange though that such thing is not directly supported by the language, and you have to use tricks. This seems to be a much worse alternative.

In the short time I tried C#, this was the only real problem I had with it. It’s a true programming language. I don’t know if it is good or bad because I really haven’t used it enough, but against all my prejudice, it seems to be quite usable. I think there are some design flaws in .NET, and it would be difficult to separate C# from .NET, but unless I used it much more, I’d rather not comment on that aspect of the language. Also MS seems to be in love with interfaces which clearly appear in C#, and that in my opinion is an unnecessary solution to a problem that doesn’t exist, but it has little to do with this blog post.

I would like to create a “solution” (as projects are called in VS), that requires me to dig deeper into the depths of both the language and .NET, but I can’t think of anything right now that would be worth it. Suggestions are welcome 😉

Categories: Rant Tags: , ,