Related
I tried to google but didn't find a decent tutorial with snippet code.
Does anyone used typed DataSets\DataTable in c# ?
Is it from .net 3.5 and above?
To answer the second parts of the question (not the "how to..." from the title, but the "does anyone..." and "is it...") - the answer would be a yes, but a yes with a pained expression on my face. For new code, I would strongly recommend looking at a class-based model; pick your poison between the many ORMs, micro-ORMs, and raw ADO.NET. DataTable itself does still have a use, in particular for processing and storing unpredictable data (where you have no idea what the schema is in advance). By the time you are talking about typed data-sets, I would suggest you obviously know enough about the type that this no longer applies, and an object-model is a very valid alternative.
It is still a supported part of the framework, and it is still in use as a technology. It has some nice features like the diff-set. However, most (if not all) of that is also available against an object-based design, with classes and properties (without the added overhead of the DataTable abstraction).
MSDN has guidance. It really hasn't changed since typed datasets were first introduced.
http://msdn.microsoft.com/en-us/library/esbykkzb(v=VS.100).aspx
There are tons of videos available here: http://www.learnvisualstudio.net/series/aspdotnet_2_0_data_access_and_databinding/
And I found one more tutorial here: http://www.15seconds.com/issue/031223.htm
Sparingly.... Unless you need to know to maintain legacy software, learn an ORM or two, particularly in conjunction with LINQ.
Some of my colleagues have them, the software I work on doesn't use them at all, on account of some big mouth developer getting his way again...
I've recently started using the DynamicQuery API, and it quickly became apparent that it has numerous limitations. I've found at least one improvement online: support for enum arguments, but it's pretty clear that this API is not actively maintained (if at all).
In case I'm wrong and there is somebody maintaining an improved version - please post a link!
Alternatively, a separate, active project with similar goals would also be of interest.
(Clarification: I'm looking to parse strings at runtime.)
In the end we just implemented some of the features we missed by editing the source code. Added support for passing in a static class as an "external" (DynamicQuery's terminology), support for calling methods on this static class, and type inference if any such methods are generic.
I suspect there isn't much demand for this, so I didn't bother making it available anywhere. Let me know if you think otherwise.
Edit: due to a request, DynamicQuery Enhanced is now available on BitBucket. Expect to be underwhelmed; take a look at this Info and this list of tweaks.
I've seen PredicateBuilder before mentioned (here on Stackoverflow) as an alternative. I've not used it though, but it might be useful to you.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I've recently purchased a Mac and use it primarily for C# development under VMWare Fusion. With all the nice Mac applications around I've started thinking about Xcode lurking just an install click away, and learning Objective-C.
The syntax between the two languages looks very different, presumably because Objective-C has its origins in C and C# has its origins in Java/C++. But different syntaxes can be learnt so that should be OK.
My main concern is working with the language and if it will help to produce well-structured, readable and elegant code. I really enjoy features such as LINQ and var in C# and wonder if there are equivalents or better/different features in Objective-C.
What language features will I miss developing with Objective-C? What features will I gain?
Edit: The framework comparisons are useful and interesting but a language comparison are what this question is really asking (partly my fault for originally tagging with .net). Presumably both Cocoa and .NET are very rich frameworks in their own right and both have their purpose, one targeting Mac OS X and the other Windows.
Thank you for the well thought out and reasonably balanced viewpoints so far!
No language is perfect for all tasks, and Objective-C is no exception, but there are some very specific niceties. Like using LINQ and var (for which I'm not aware of a direct replacement), some of these are strictly language-related, and others are framework-related.
(NOTE: Just as C# is tightly coupled with .NET, Objective-C is tightly coupled with Cocoa. Hence, some of my points may seem unrelated to Objective-C, but Objective-C without Cocoa is akin to C# without .NET / WPF / LINQ, running under Mono, etc. It's just not the way things are usually done.)
I won't pretend to fully elaborate the differences, pros, and cons, but here are some that jump to mind.
One of the best parts of Objective-C is the dynamic nature — rather than calling methods, you send messages, which the runtime routes dynamically. Combined (judiciously) with dynamic typing, this can make a lot of powerful patterns simpler or even trivial to implement.
As a strict superset of C, Objective-C trusts that you know what you're doing. Unlike the managed and/or typesafe approach of languages like C# and Java, Objective-C lets you do what you want and experience the consequences. Obviously this can be dangerous at times, but the fact that the language doesn't actively prevent you from doing most things is quite powerful. (EDIT: I should clarify that C# also has "unsafe" features and functionality, but they default behavior is managed code, which you have to explicitly opt out of. By comparison, Java only allows for typesafe code, and never exposes raw pointers in the way that C and others do.)
Categories (adding/modifying methods on a class without subclassing or having access to source) is an awesome double-edged sword. It can vastly simplify inheritance hierarchies and eliminate code, but if you do something strange, the results can sometimes be baffling.
Cocoa makes creating GUI apps much simpler in many ways, but you do have to wrap your head around the paradigm. MVC design is pervasive in Cocoa, and patterns such as delegates, notifications, and multi-threaded GUI apps are well-suited to Objective-C.
Cocoa bindings and key-value observing can eliminate tons of glue code, and the Cocoa frameworks leverage this extensively. Objective-C's dynamic dispatch works hand-in-hand with this, so the type of the object doesn't matter as long as it's key-value compliant.
You will likely miss generics and namespaces, and they have their benefits, but in the Objective-C mindset and paradigm, they would be niceties rather than necessities. (Generics are all about type safety and avoiding casting, but dynamic typing in Objective-C makes this essentially a non-issue. Namespaces would be nice if done well, but it's simple enough to avoid conflicts that the cost arguably outweighs the benefits, especially for legacy code.)
For concurrency, Blocks (a new language feature in Snow Leopard, and implemented in scores of Cocoa APIs) are extremely useful. A few lines (frequently coupled with Grand Central Dispatch, which is part of libsystem on 10.6) can eliminates significant boilerplate of callback functions, context, etc. (Blocks can also be used in C and C++, and could certainly be added to C#, which would be awesome.) NSOperationQueue is also a very convenient way to add concurrency to your own code, by dispatching either custom NSOperation subclasses or anonymous blocks which GCD automatically executes on one or more different threads for you.
I've been programming in C, C++ and C# now for over 20 years, first started in 1990. I have just decided to have a look at the iPhone development and Xcode and Objective-C. Oh my goodness... all the complaints about Microsoft I take back, I realise now how bad things code have been. Objective-C is over complex compared to what C# does. I have been spoilt with C# and now I appreciate all the hard work Microsoft have put in. Just reading Objective-C with method invokes is difficult to read. C# is elegant in this. That is just my opinion, I hoped that the Apple development language was a good as the Apple products, but dear me, they have a lot to learn from Microsoft. There is no question C#.NET application I can get an application up and running many times faster than XCode Objective-C. Apple should certainly take a leaf out of Microsoft's book here and then we'd have the perfect environment. :-)
No technical review here, but I just find Objective-C much less readable.
Given the example Cinder6 gave you:
C#
List<string> strings = new List<string>();
strings.Add("xyzzy"); // takes only strings
strings.Add(15); // compiler error
string x = strings[0]; // guaranteed to be a string
strings.RemoveAt(0); // or non-existant (yielding an exception)
Objective-C
NSMutableArray *strings = [NSMutableArray array];
[strings addObject:#"xyzzy"];
[strings addObject:#15];
NSString *x = strings[0];
[strings removeObjectAtIndex:0];
It looks awful. I even tried reading 2 books on it, they lost me early on,
and normally I don't get that with programming books / languages.
I'm glad we have Mono for Mac OS, because if I'd had to rely on Apple
to give me a good development environment...
Manual memory management is something beginners to Objective-C seems to have most problem with, mostly because they think it is more complex than it is.
Objective-C and Cocoa by extension relies on conventions over enforcement; know and follow a very small set of rules and you get a lot for free by the dynamic run-time in return.
The not 100% true rule, but good enough for everyday is:
Every call to alloc should be matched with a release at the end of the current scope.
If the return value for your method has been obtained by alloc then it should be returned by return [value autorelease]; instead of being matched by a release.
Use properties, and there is no rule three.
The longer explanation follows.
Memory management is based on ownership; only the owner of an object instance should ever release the object, everybody else should always do nothing. This mean that in 95% of all code you treat Objective-C as if it was garbage collected.
So what about the other 5%? You have three methods to look out for, any object instance received from these method are owned by the current method scope:
alloc
Any method beginning with the word new, such as new or newService.
Any method containing the word copy, such as copy and mutableCopy.
The method have three possible options as of what to do with it's owned object instances before it exits:
Release it using release if it is no longer needed.
Give ownership to the a field (instance variable), or a global variable by simply assigning it.
Relinquish ownership but give someone else a chance to take ownership before the instance goes away by calling autorelease.
So when should you pro-actively take ownership by calling retain? Two cases:
When assigning fields in your initializers.
When manually implementing setter method.
Sure, if everything you saw in your life is Objective C, then its syntax looks like the only possible. We could call you a "programming virgin".
But since lots of code is written in C, C++, Java, JavaScript, Pascal and other languages, you'll see that ObjectiveC is different from all of them, but not in a good way. Did they have a reason for this? Let's see other popular languages:
C++ added a lot extras to C, but it changed the original syntax only as much as needed.
C# added a lot extras compared to C++ but it changed only things that were ugly in C++ (like removing the "::" from the interface).
Java changed a lot of things, but it kept the familiar syntax except in parts where the change was needed.
JavaScript is a completely dynamic language that can do many things ObjectiveC can't. Still, its creators didn't invent a new way of calling methods and passing parameters just to be different from the rest of the world.
Visual Basic can pass parameters out of order, just like ObjectiveC. You can name the parameters, but you can also pass them the regular way. Whatever you use, it's normal comma-delimited way that everyone understands. Comma is the usual delimiter, not just in programming languages, but in books, newspapers, and written language in general.
Object Pascal has a different syntax than C, but its syntax is actually EASIER to read for the programmer (maybe not to the computer, but who cares what computer thinks). So maybe they digressed, but at least their result is better.
Python has a different syntax, which is even easier to read (for humans) than Pascal. So when they changed it, making it different, at least they made it better for us programmers.
And then we have ObjectiveC. Adding some improvements to C, but inventing its own interface syntax, method calling, parameter passing and what not. I wonder why didn't they swap + and - so that plus subtracts two numbers. It would have been even cooler.
Steve Jobs screwed up by supporting ObjectiveC. Of course he can't support C#, which is better, but belongs to his worst competitor. So this is a political decision, not a practical one. Technology always suffers when tech decisions are made for political reasons. He should lead the company, which he does good, and leave programming matters to real experts.
I'm sure there would be even more apps for iPhone if he decided to write iOS and support libraries in any other language than ObjectiveC. To everyone except die-hard fans, virgin programmers and Steve Jobs, ObjectiveC looks ridiculous, ugly and repulsive.
One thing I love about objective-c is that the object system is based on messages, it lets you do really nice things you couldn't do in C# (at least not until they support the dynamic keyword!).
Another great thing about writing cocoa apps is Interface Builder, it's a lot nicer than the forms designer in Visual Studio.
The things about obj-c that annoy me (as a C# developer) are the fact that you have to manage your own memory (there's garbage collection, but that doesn't work on the iPhone) and that it can be very verbose because of the selector syntax and all the [ ].
As a programmer just getting started with Objective-C for iPhone, coming from C# 4.0, I'm missing lambda expressions, and in particular, Linq-to-XML. The lambda expressions are C#-specific, while the Linq-to-XML is really more of a .NET vs. Cocoa contrast. In a sample app I was writing, I had some XML in a string. I wanted to parse the elements of that XML into a collection of objects.
To accomplish this in Objective-C/Cocoa, I had to use the NSXmlParser class. This class relies on another object which implements the NSXMLParserDelegate protocol with methods that are called (read: messages sent) when an element open tag is read, when some data is read (usually inside the element), and when some element end tag is read. You have to keep track of the parsing status and state. And I honestly have no idea what happens if the XML is invalid. It's great for getting down to the details and optimize performance, but oh man, that's a whole lot of code.
By contrast, here's the code in C#:
using System.Linq.Xml;
XDocument doc = XDocument.Load(xmlString);
IEnumerable<MyCustomObject> objects = doc.Descendants().Select(
d => new MyCustomObject{ Name = d.Value});
And that's it, you've got a collection of custom objects drawn from XML. If you wanted to filter those elements by value, or only to those that contain a specific attribute, or if you just wanted the first 5, or to skip the first 1 and get the next 3, or just find out if any elements were returned... BAM, all right there in the same line of code.
There are many open-source classes that make this processing a lot easier in Objective-C, so that does much of the heavy lifting. It's just not this built in.
*NOTE: I didn't actually compile the code above, it's just meant as an example to illustrate the relative lack of verbosity required by C#.
Probably most important difference is memory management. With C# you get garbage collection, by virtue of it being a CLR based language. With Objective-C you need to manage memory yourself.
If you're coming from a C# background (or any modern language for that matter), moving to a language without automatic memory management will be really painful, as you will spend a lot of your coding time on properly managing memory (and debugging as well).
Here's a pretty good article comparing the two languages:
http://www.coderetard.com/2008/03/16/c-vs-objective-c/
Other than the paradigm difference between the 2 languages, there's not a lot of difference. As much as I hate to say it, you can do the same kind of things (probably not as easily) with .NET and C# as you can with Objective-C and Cocoa. As of Leopard, Objective-C 2.0 has garbage collection, so you don't have to manage memory yourself unless you want to (code compatibility with older Macs and iPhone apps are 2 reasons to want to).
As far as structured, readable code is concerned, much of the burden there lies with the programmer, as with any other language. However, I find that the message passing paradigm lends itself well to readable code provided you name your functions/methods appropriately (again, just like any other language).
I'll be the first to admit that I'm not very familiar with C# or .NET. But the reasons Quinn listed above are quite a few reasons that I don't care to become so.
The method calls used in obj-c make for easily read code, in my opinion much more elegant than c# and obj-c is built on top of c so all c code should work fine in obj-c. The big seller for me though is that obj-c is an open standard so you can find compilers for any system.
Today I found out about an interface I'd never heard of before: IGrouping
IEnumerable<IGrouping<YourCategory, YourDataItem>>
I am fortunate to have access to some of the best programming books available, but seldom do I come across these kinds of gems in those books. Blogs and podcasts work, but that approach is somewhat scattershot. Is there a better way to learn these things, or do I need to sift through the entire MSDN library to discover them?
Eric Lippert's blog. The real guts of C# - why there are some limitations which might seem arbitrary at first sight, how design decisions are made, etc.
Alternatively, for more variety, look at the Visual C# Developer Center - there's a whole range of blogs and articles there.
Oh, and read the C# spec. No, I mean it - some bits can be hard to wade through (I'm looking at you, generic type inference!) but there's some very interesting stuff in there.
The best place to start is Jon Skeet's C# Coding blog: http://msmvps.com/blogs/jon_skeet/
He regularly covers stuff you won't see anywhere else.
How about the Hidden Features series of questions?
Hidden Features of C#
Hidden Features of ASP.NET
And many more...
I personally like the way of discovering hidden features on my own while solving a specific problem. In the end, a hidden feature that you never needed to get something done is of questionable value. It just adds clutter to the brain.
The way to do it is to use the MSDN library to look things up. Then take a little time to look around what you found.
That's especially important with the pure API documentation. For instance, I just browsed to http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx (note how that URL is formed). When I look in the Contents pane on the left, I see everything from XmlDocument (and XmlDocumentFragment) all the way down to XmlReader. In the middle are some things I rarely or never use, like XmlNamespaceScope and XmlNodeOrder.
From time to time, spend a little time on "abstract knowledge". Sometimes, it's good to look up from the trees to learn your way around the forest. You never know when you'll need something you've learned to get you out of the woods.
For the people who don't know IGrouping:
http://msdn.microsoft.com/en-us/library/bb344977.aspx
I often read useful stuff on the Viual Studio Startup page and start clicking around to other keywords/areas. Not too promote StackOverflow too much, but you'll find some hidden gems here as well, simply by looking at how other people write code.
For example:
Hidden Features of C#?
This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:
Firstly: Given an established C# project, what are some decent ways to speed it up beyond just plain in-code optimization?
Secondly: When writing a program from scratch in C#, what are some good ways to greatly improve performance?
Please stay away from general optimization techniques unless they are C# specific.
This has previously been asked for Python, Perl, and Java.
Off the top of my head:
Replace non-generic variants of container classes by their generic counterparts
Cut down on boxing/unboxing. Specifically, use generics where possible and generally avoid passing value types as object.
For dialogs using many dynamic controls: suspend drawing until after inserting all controls by using SuspendLayout/ResumeLayout. This helps especially when using layout containers.
Unfortunately, relatively few optimisations are language specific. The basics apply across languages:
Measure performance against realistic loads
Have clearly-defined goals to guide you
Use a good profiler
Optimise architecture/design relatively early
Only micro-optimise when you've got a proven problem
When you've absolutely proved you need to micro-optimise, the profiler tends to make it obvious what to look for - things like avoiding boxing and virtual calls.
Oh, one thing I can think of which is .NET-specific: if you need to make a call frequently and are currently using reflection, convert those calls into delegates.
EDIT: The other answers suggesting using generics and StringBuilder etc are of course correct. I (probably wrongly) assumed that those optimisations were too "obvious" ;)
One simple thing is to ensure that your build configuration is set to "Release". This will enable optimizations and eliminate debugging information, making your executable smaller.
More info on MSDN if needed.
Use a decent quality profiler and determine where your bottlenecks are.
Then start asking how to improve performance.
Anyone who makes any blanket statements like 'avoid reflection' without understanding both your performance profile and your problem domain should be shot (or at least reeducated). And given the size of the .Net landscape it's pretty much meaningless to talk about C# optimization: are we talking about WinForms, ASP.Net, BizTalk, Workflow, SQL-CLR? Without the context even general guidelines may be at best a waste of time.
Consider also what you mean by 'speed it up' and 'improve performance'. Do you mean greater resource efficiency, or lower perceived wait time for an end user (assuming there is one)? These are very different problems to solve.
Given the forum I feel obliged to point out that there some quite good coverage on these topics in Code Complete. Not C# specific mind. But that's a good thing. Bear in mind the language-specific micro-optimisations might well be subsumed into the next version of whatever compiler you're using, And if the difference between for and foreach is a big deal to you you're probably writing C++ anyway, right?
[I liked RedGate's ANTS Profiler, but I think it could be bettered]
With that out the way, some thoughts:
Use type(SomeType) in preference to
instance.GetType() when possible
Use
foreach in preference to for
Avoid
boxing
Up to (I think) 3 strings
it's ok to do StringA + StringB +
StringC. After that you should use a
StringBuilder
Use StringBuilder rather than lots of string concatenation. String objects are atomic, and any modification (appending, to-upper, padding, etc) actually generate a completely new string object rather than modifying the original. Each new string must be allocated and eventually garbage collected.
A generalization of the prior statement: Try to reuse objects rather than creating lots and lots of them. Allocation and garbage collection may be easy to do, but they hit your performance.
Be sure to use the provided Microsoft libraries for most things. The classes provided by the Framework often use features that are unavailable or difficult to access from your own C# code (i.e. making calls out to the native Windows API). The built-in libraries are not always the most efficient, but more often than not.
Writing asynchronous apps has never been easier. Look into things like the BackgroundWorker class.
Try not to define Structs unless you really need them. Class instance variables each hold a reference to the actual instance, while struct instance variables each hold a separate copy.
Use composition instead of inheritance, limit boxing/unboxing, use generic collections, use foreach loops instead of for{} with a counter, and release resources with the standard Dispose pattern.
These are covered in detail in the excellent book Effective C#.
Profile your code. Then you can at least have an understanding of where you can improve. Without profiling you are shooting in the dark...
A lot of slowness is related to database access. Make your database queries efficient and you'll do a lot for your app.
I have the following MSDN article bookmarked, and find it to be a good general reference.
Improving .NET application pefformance
NGEN will help with some code, but do not bank on it.
Personally, if your design is bad/slow, there is not much you can do.
The best suggestion in such a case, is to implement some form of caching of expensive tasks.
I recomend you those books:
Effective C#.
More Effective C#
Don't use to much reflection.
Use Ngen.exe (Should come shipped with Visual Studio.)
http://msdn.microsoft.com/en-us/library/6t9t5wcf(VS.80).aspx
The Native Image Generator (Ngen.exe) is a tool that improves the performance of managed applications. Ngen.exe creates native images, which are files containing compiled processor-specific machine code, and installs them into the native image cache on the local computer. The runtime can use native images from the cache instead using the just-in-time (JIT) compiler to compile the original assembly.
In addition to the coding best practices listed above including using StringBuilders when appropriate and items of that nature.
I highly recommend using a code profiling tool such as ANTs Profiler by RedGate. I have found that after taking the standard steps for optimization that using Profiler I can further optimize my code by quickly identifying the area(s) of code that are most heavily hit by the application.
This is true for any language, not just C#
For an existing app, don't do anything until you know what's making it slow. IMHO, this is the best way.
For new apps, the problem is how programmers are taught. They are taught to make mountains out of molehills. After you've optimized a few apps using this you will be familiar with the problem of what I call "galloping generality" - layer upon layer of "abstraction", rather than simply asking what the problem requires. The best you can hope for is to run along after them, telling them what the performance problems are that they've just put in, so they can take them out as they go along.
Caching items that result from a query:
private Item _myResult;
public Item Result
{
get
{
if (_myResult == null)
{
_myResult = Database.DoQueryForResult();
}
return _myResult;
}
}
Its a basic technique that is frequently overlooked by starting programmers, and one of the EASIEST ways to improve performance in an application.
Answer ported from a question that was ruled a dupe of this one.
For Windows Forms on XP and Vista: Turn double buffering on across the board. It does cause transparency issues, so you would definitely want to test the UI:
protected override System.Windows.Forms.CreateParams CreateParams {
get {
CreateParams cp = base.CreateParams;
cp.ExStyle = cp.ExStyle | 0x2000000;
return cp;
}
}