C# 3.0 in a nutshell

Joseph Albahari, Ben Albahari, Peter Drayton

Mentioned 18

Offers a reference to key C# programming concepts covering language elements, syntax, datatypes, and tasks.

More on Amazon.com

Mentioned in questions and answers.

Based on this recent question, I don't understand the answer provided. Seems like you should be able to do something like this, since their scopes do not overlap

static void Main()
{
  {
    int i;
  }
  int i;
}

This code fails to compile with the following error:

A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'child' scope to denote something else

"The scope of local or constant variable extends to the end of the current block. You cannot declare another local variable with the same name in the current block or in any nested blocks." C# 3.0 in a Nutshell, http://www.amazon.com/3-0-Nutshell-Desktop-Reference-OReilly/dp/0596527578/

"The local variable declaration space of a block includes any nested blocks. Thus, within a nested block it is not possible to declare a local variable with the same name as a local variable in an enclosing block." Variable Scopes, MSDN, http://msdn.microsoft.com/en-us/library/aa691107%28v=vs.71%29.aspx

On a side note, this is quite the opposite that of JavaScript and F# scoping rules.

I want to make a deep copy of a LINQ to XML XElement. The reason I want to do this is there are some nodes in the document that I want to create modified copies of (in the same document). I don't see a method to do this.

I could convert the element to an XML string and then reparse it, but I'm wondering if there's a better way.

Lifted directly from C# 3.0 in a Nutshell:

When a node or attribute is added to an element (whether via functional construction or an Add method) the node or attribute's Parent property is set to that element. A node can have only one parent element: if you add an already parented node to a second parent, the node is automatically deep-cloned. In the following example, each customer has a separate copy of address:

var address = new XElement ("address",
                  new XElement ("street", "Lawley St"),
                  new XElement ("town", "North Beach")
              );
var customer1 = new XElement ("customer1", address);
var customer2 = new XElement ("customer2", address);

customer1.Element ("address").Element ("street").Value = "Another St";
Console.WriteLine (
  customer2.Element ("address").Element ("street").Value);   // Lawley St

This automatic duplication keeps X-DOM object instantiation free of side effects—another hallmark of functional programming.

It seems that C# 3 hit me without me even noticing, could you guys tell me about good in depth guides to C# 3? from lambda to linq to everything else that was introduced with the third version of the language.

Printed books would be nice, but online guides would be even better!

I've found C# 3.0 in a Nutshell to be very useful.

I found Pro LINQ: Language Integrated Query in C# 2008 to be very helpful for this. It has a chapter which covers all the new language features in 3, and of course the rest of the book goes into a deep dive on LINQ. I would highly recommend it.

Picking up C#, can't seem to find any useful reference to this, other than examples.

So, what is Dim in C#?

I can suggest Learning C# 3.0 (and later, maybe C# 3.0 in a Nutshell and C# in Depth) to learn C#. It's probably a good idea to learn the language fundamentals and start "thinking in C#", instead of trying to "translate" or "convert" your thoughts from VB to C# (or any other language, for that matter).


Edit: That said; you do want to compare the new language you're learning to the one(s) you already know whilst you go along, to learn the differences between the languages. In my opinion, when learning a new language, it's more about grasping the principles and fundamental differences :)

I have 6+ years of C/C++ experience. Tomorrow starts a university assignment where I will have to use C#. Therefore I would like to have a list of links/resources which you think important or an extensive tutorial - in short everything you think worthy.

Coding style, best practices, ...

(I don't know any specifics about the C# environment I will be using(IDE, OS, w/e), the first meeting is tomorrow evening).

(I have never coded C# before)

One more thing: I would like to work using Linux (kubuntu 10.4). IDE / environment / tutorial suggestions regarding Linux specifically are very welcome.

Thanks for your help!

Quick introduction to syntax + essentials of a language.

Obvious link to an overview of a platform :)

Best practices discussed here, on SO

It's better to read books of course, when a sufficient amount of time is available. I personally started to learn c# by reading Pro C# 2008 and the .NET 3.5 Platform

P.S. If you want to use linux, here you go:

IDE

Framework

I am currently reading Albahari's C# 3.0 in a Nutshell and on pg. 241, whilst talking about Array indexing, he says this:

Nonzero-based arrays are not CLS (Common Language Specification)-compliant

What does it mean exactly, for nonzero arrays to not be CLS compliant ? And what implications does it have on your code?

[Update]

Here is a link to the page of the book.

The CLS (Common Language Specification) lays the groundwork for a common set of rules for compliance that guarantees that other languages (VB.NET, F#, etc.) can use assemblies that you have built with C#. A nonzero-based array would not be compliant as other languages expect arrays to be zero-based.

Here is an example that is easier to understand:

class Foo
{
    public void Bar() { }
    public void bar() { } 
}

This type would not be CLS compliant since it contains two members that differ in name only by type. How would someone using VB.NET disambiguate between Bar and bar since the VB.NET compiler is not case-sensitive?

So basically the CLS is a bunch of rules like this to guarantee interoperability between languages.

What is the proper technique to have ThreadA signal ThreadB of some event, without having ThreadB sit blocked waiting for an event to happen?

i have a background thread that will be filling a shared List<T>. i'm trying to find a way to asynchronously signal the "main" thread that there is data available to be picked up.


i considered setting an event with an EventWaitHandle object, but i can't have my main thread sitting at an Event.WaitOne().


i considered having a delegate callback, but a) i don't want the main thread doing work in the delegate: the thread needs to get back to work adding more stuff - i don't want it waiting while the delegate executes, and b) the delegate needs to be marshalled onto the main thread, but i'm not running a UI, i have no Control to .Invoke the delegate against.


i considered have a delegate callback that simply starts a zero interval System.Windows.Forms.Timer (with thread access to the timer synchronized). This way the thread only needs to be stuck as it calls

Timer.Enabled = true;

but that seems like a hack.

In the olden days my object would have created a hidden window and had the thread post messages to that hidden windows' HWND. i considered creating a hidden control, but i gather that you cannot .Invoke on a control with no handle created. Plus, i have no UI: my object could have been created on a web-server, service, or console, i don't want there to be a graphical control appearing - nor do i want to compile a dependency on System.Windows.Forms.


i considered having my object expose an ISynchronizeInvoke interface, but then i would need to implement .Invoke(), and that's my problem.


What is the proper technique to have thread A signal thread B of some event, without having thread B sit blocked waiting for an event to happen?

There are many ways to do this, depending upon exactly what you want to do. A producer/consumer queue is probably what you want. For an excellent in-depth look into threads, see the chapter on Threading (available online) from the excellent book C# 3.0 in a Nutshell.

Where do you get the best in-depth information for C# programming? I'm looking for tutorials, examples, blogs, specialized forums etc. dedicated to c#.

I recommend you Jeffrey Richter's "CLR via C#" book. You can learn CLR features and how does c# implement them. Also you can learn a lot about multithreading in c#, localization, appdomains etc. .net topics.

You can't go wrong with these:

Is there any good tutorial to learn C# with mono? So far, google hasn't been helpful because most tutorial are for Visual Studio.

I am a Java developer, so I am familiar with Object Oriented ideas.

My goal, is to be able to develop a small portable application with a SQLite backend.

Thanks

The language itself will be the same whatever tutorial you use. Really you just need to know how to compile code using Mono instead of Visual Studio. The basic command line you'll want to use is:

gmcs Foo.cs Bar.cs

with these as the most important command line options:

  • -target - whether you want to build a console app (-target:exe), a Windows Forms app (winexe), a class library (library) or a module (module)
  • -r - add a reference to another assembly (e.g. -r:Foo.dll) - most of the common assemblies should be added automatically
  • -out - specify the output filename (e.g. -out:Foo.exe)
  • /? - find out about other command line options :)

In terms of reading material, I can recommend C# 3.0 in a Nutshell as it covers the language and the core framework classes.

There's a lot to C# & ASP.net. Where should I start? What should I not bother focusing on?

Should I learn Winforms then WPF? Ditto for webforms / Silverlight? Should I learn ASP.MVC or classic ASP.NET? If both, which first?

In the either/or cases - which will make more sense having known the other first?

What major .NET feature(s) should I learn upfront that will open the doors of understanding to what lies ahead?

I am deliberately not mentioning fundamentals like value / reference Types, Classes, object-oriented concepts, etc since they should come first, before specifics. Here, I am interested in specifics.

[edit - added detail of what my goals are] Good points raised - "what do I want to write"?

Basically, an intranet application that monitors a set of documents and implements a workflow as a change control process. The app will also audit the documents and report problems, self-correcting common errors. A lot of the parameters will need to be end-user definable and pluggable. The document format needs to be adaptable to different proprietary formats although they are fundamentally the same. The app will be very modular.

I'm leaning towards a web interface because the client specs & admin rights will vary - a browser is really the only thing I can count on.

As you can see, it's a bit of everything.

What do you want to write? If you want to write a Windows client-side app, look into WinForms and WPF (no real need to learn WinForms before WPF, other than the way that a lot of tutorials/books will probably compare WPF concepts with WinForms concepts). If you're looking at a web app, then ASP.NET or ASP.MVC - I don't know whether you really need the "normal" ASP.NET before MVC.

Silverlight is a bit of both, in a way - rich client probably talking to a server for interesting data etc.

Before learning any of these though, I suggest you learn the fundamentals which are one step up from the topics you mentioned - things like how text works in .NET (including encodings and regular expressions), I/O, perhaps threading. Oh, and LINQ :) There are a few books which are very good on this front:

I highly recommend the following books, for learning about whats new in ASP.NET 3.5

I had the same question when I moved from Classic ASP to .NET 2.0... .NET is huge: so where should I start?

What i did was put my hand dirty and started slow, take a project (in my case was a very important project - a finance web app that would cover and automatize all 4 persons work) and start to implement, every time I didn't know how to accomplish something or I had an idea in ASP but not in ASP.NET I would go to www.asp.net or 4GuysFromRolla website and search for examples, copy/paste, understand what I was doing and ... continue to the next wall.

Took me 6 month to have everything up and running but was worst it! now that passed almost 3 years I know I did the right choice but back then ... I was scared!

now... you refer .NET 3.5, it has a bunch of new things like extensions, linq, etc... I would go by the simple part and when the times comes, "maybe I can use LINQ here, let me search how to use it on this part"

hope you follow your own path and buy some reference book so you can read something new and have a reference whenever you need "ahhh, I read this somewhere in the book, let me search... where was it?"

I bought Professional ASP.NET from Wrox as a reference book, and even today I go there to see new things, even when I'm started to use .NET 3.5, the idea is there, there is only a new way to accomplishing it.

How can I increase my proficiency in programming? I have a grasp of the basics of C#, but don't feel too confident about my ability.

read lots of code, write lots of code and keep a copy of C# 3.0 in a nutshell handy.

I am new to C#, C++ and .Net.

I am currently returning to programming from a stint in Networking and Cisco engineering. I used to program on IBM mainframes etc using Cobol, assembler, easytrieve, Rexx and clist etc so the command syntax is reasonably familiar to me as are programming standards and structures.

However I am having quite a bit of trouble getting to grips with the BCL and understanding the various components and what each is designed for and which is best to use in various situations, and in fact how some are actually used and coded.

I am often scratching my head wondering how the code came about from the descriptions I have found about the BCL components. Basically how to use them and code them seems to be a black art with no intuitive means at all.

So my question is, apart from the msdn library, which I am finding to be a bit over complicated for my current needs, is there any good reference book, site, pdf that can give me a reasonable description, usage notes etc of the most commonly used .NET components such as System.IO etc ?

I have read a few book on C# etc and have found a small program that does part of what I need to do in a project I have, requiring acces to devices via RS-232 ports, but when decoding the program I find myself wondering why the person used the components he did and how would I know which components I should use when I make the changes I need to and add in the extra code that I require and how do I actually use these components when I do find them ?

I do realise a lot of this will be down to plain old experience, but a helping hand in the right direction would really help a lot.

Many thanks, George.

C# 3.0 in a Nutshell is good for this, as is Accelerated C# 2008. I think I'd personally recommend Nutshell more.

Note that the next edition of Nutshell is being prepared - but I don't know what the timeframe is. (I'm sure there'll be a slew of books for .NET 4.0.)

(Note of bias: I'm a tech reviewer for C# 4.0 in a Nutshell, so I'm clearly not 100% impartial.)

Good day!

I'm currently building a small website where I write down problems that arise and answers to them for others to see. Currently I'm using a DAL much like the one described here. Now I have been looking at other models, and in particular linq based models using Linq2SQL and the ADO.net Entries framework. I realize I'm moving the data access to the code layer in a way since I'm then filtering out for example a toplist with linq queries. The reason I started doing this was because the DAL was not really syncing up with the DB at all times and nullable types became not nullable when I changed something in the DB. Then if I would reimport the tables into the data table my queries would be lost.

My simple question is really, if you want a good DAL for ASP.net today, what would that be? Suggestions, experiences are more than welcome.

I personally preffer LINQ to SQL and ADO.NET Entity Framework. Microsoft guys also use those technologies in their latest projects (take a look at KOBE project for example). Thus, Microsoft recommends those two as well.

Though.. sometimes I use Data Access Application block from Enterprise Library and manual DAL coding when I need maximum control over it's functionality and implementation.

Other alternatives are: NHibernate, SubSonic, different ORM solutions like LLBLGen Pro.


Great books on this subject:


Related tools:

  • LINQPad is also a great way to learn LINQ: it comes preloaded with 200 examples from the book, C# 3.0 in a Nutshell. There's no better way to experience the coolness of LINQ and functional programming.

I want to learn C# and the .Net Framework as well.

I have no idea on the Microsoft .Net and C# framework but I once programmed on their Microsoft Visual Basic 6 with experience on making COM Components (OCX and DLL).

I have an experience programming on java and have fair knowledge of Object Oriented Technology. But I am currently confused on the number of books currently written for C#.

I want a book that will not explain me the for loop or iterative looping on one chapter but more on the language itself. I've heard that C# is a close cousin of Java so I think I just want to know the syntax.

Since I dont know C# and .Net framework< i would like a book that could focus on them.

Currently, as I have viewed from the net. I have this list of books:

  • Head First C#
  • Illustrated C#
  • MS C# 2008 Step By STep
  • Illustrated C#
  • C# 3.0 in a Nutshell
  • Wrox Beginning C# 2008
  • C# in Depth

From the review in amazon, they all look good but I dont know which one of them or that is not in the list that I have would suit me.

I definitely want to learn C# so hopefully someone can help me

Effective C# and More Effective C# by Bill Wagner are worth a read.

Or Effective C# and More Effective C# if you're in the States.

C# 3.0 in a Nutshell has really helped me understand C# in depth; I recommend it for anyone.

Although I wouldn't say it's really a beginner's book per ce.

alt text

I'm a fan of the CLR via C#, by Jeffrey Richter, a man very, very wise in C#-fu.

Also, check out our very own Jon Skeet's C# in Depth.

Both are great reads.

I am an senior-slash-"advanced" C#/.NET developer, currently using 3.5 Framework with WPF/WCF and Silverlight (WPF/E). I have come up right through 1.0 and 2.0 and so am well versed with the evolution of .NET. My next project could be "back" into 2.0 Framework, but with enough complexity (and time pressure) so as to call on "expert" skills, not just "advanced" ones.

Thus I am looking for a book with comprehensive coverage of the 2.0 Framework, primarily the organization and use of the libraries (by which, yes, I really just mean "the Framework"...) available in that rev. I want to have a complete, organized reference on hand for what tools are available in the box, so to speak, to choose the right ones at each step and not re-invent any wheels.

I own and love "CLR via C#", but this isn't a question about the CLR, it's about libraries (Framwork) primarily, and also interfacing techniques to .NET-supported related products.

If I "subtract out" my existing 3.0/3.5 knowledge/experience, I might say that I've only ever thoroughly investigated and used some 50-75% of the 2.0 Framework - so what I'd like to see is an authoritative guide to the full 100%. Doesn't need rigorous details or comprehensive examples, but rather a full assessment of scale and scope to be able to design and implement effective solutions in .net 2.0 "the right way".

For WinForms programming, the book that has proved itself most useful to me is Windows Forms 2.0 Programming. If there isn't a single book that has everything you're looking for, I think this book would be part of the collection comprising the next best thing.

C# 3.0 in a Nutshell covers parts of the framework in sufficient detail. I find it to be a very useful book to have around.

Programming Microsoft Visual C# 2005: The Base Class Library specifically covers the framework, but in my opinion the Nutshell book is better and you can always find additional information on MSDN.

Windows Forms Programming in C# covers WinForms in detail, or you may want to look at Chris Sells' book on WPF instead. I'm not familiar with the latter, but the first is okay.

It sounds like you have a good grasp on C# itself, so you probably want to know what was in 2.0 that isn't in 3.0 or 3.5. For this reason, you might be interested in some of the following resources, namely the C# 2.0 standard:

I particularly like the C# 2.0 Complete Reference book, and keep a copy on my desk at home, but the C# 2.0 standard is incomparably good as well; it's just a question of whether you can stay awake long enough to get through any of it. :)

I recently installed the Mono Framework, .net 3.5 f/w and MonoDevelop (hint: I'm trying to switch over from PHP to C#3 + .net)
Even though the Mono installer states that it has installed XSP2 (I can start XSP independently from the context menu), MonoDevelop says that it cannot find XSP2.
Bonus Q1: When you have an asp.net app, what are the executable scripts* (ie. .php for PHP)?
Bonus Q2: What would be the best way to set up my development box for asp.net development? (For php I use apache2+mysqlce+php, so I would prefer something that adds on to apache, like mod_mono -- but I wanted to ask...)
Bonus Q3: Any general "non-newbieistic" help source apart from MSDN, on getting started with asp.net?

*I'm asking because it looks like the .aspx files "refer" to the .cs files in a funky sort of way... :( I'm new to this...

I'm not going to be able to help out with your MonoDevelop question and XSP2 since I haven't used Mono, but I can help with some of your other questions.

When you have an asp.net app, what are the executable scripts (ie. .php for PHP)?

ASP.NET pages have a .aspx extension (although this is configurable). When a page is first requested the ASP.NET run-time parses an ASPX file and compiles a class from it. This compiled class is executed within the ASP.NET application run-time.

.cs files are often associated with a .aspx file by development environments like Visual Studio (this isn't a requirement though you can have .aspx files independent of .cs files). The .cs file defines a class and the class compiled from the .aspx file inherits (or is a sub-type of) this class.

What would be the best way to set up my development box for asp.net development?

Again, I don't know about Mono, so I'll give my recommendation based on Microsoft tools. I'd recommend Visual Web Developer 2008 Express. It's available for free has a lot of the great features of the full-blown product and uses the built-in web server which makes configuring your environment less of a hassle.

I'd also recommend the Web Platform Installer. This will help download and install Visual Web Developer 2008 Express and get you up and running quicklu and easily with other things like the .NET Framework, IIS, SQL Server Express and even open source web applications. It's nice an easy to use.

Any general "non-newbieistic" help source apart from MSDN, on getting started with asp.net?

StackOverflow? :-)

If you're new to .NET I would recommend getting a good grasp on the language first and then ASP.NET specific stuff.

Best .NET books (in my opinion):

ASP.NET resources:

Just wondering if I needed to know c# before I can start working with asp.net,

can I learn them together?

what is a good starting point like a book or online tutorials.

thanks

Personally I'd start by learning C# without ASP.NET, preferrably via console applications. That way you can get to grips with the language and the core types (collections, I/O, text, primitives etc) without being hampered by all the extra stuff ASP.NET throws in your way.

There are various oddities in any "peripheral" technology (ASP.NET, WCF, WPF, WinForms etc) that it can be very confusing if you don't know the core stuff well: if something goes wrong, you can easily end up not having the faintest idea where to start finding the problem. Is it a misunderstanding about the language? The collections? The way that ASP.NET events are autowired? I'm sure you see what I mean :)

C# 3.0 in a Nutshell is a good book in terms of covering the language and the core framework. Then get a good ASP.NET book separately.

I wish to become a good developer in C# (especially .NET environment (i.e both windows app & web app)).

Suggest me the way to achieve the same..... It may be books, magazines, journals, code samples, etc.

Two books I found to be very helpful have been Programming C# and C# in Depth. These books are aimed at developers with existing experience in other languages, they may not be helpful if you are less experienced. Some of the other answers may have better suggestions for folks just beginning to learn programming.

You'll probably want to get Visual C# 2008 Express. It's free and very full-featured, you can get started experimenting with code very quickly and easily.

I would recommend starting with the absolute core parts of C# - learn about the type system, strings, numbers, IO, collections etc. I'd personally do this with console applications, where you don't need nearly as much code to get a result as with a GUI, and you can concentrate on the topic you're trying to learn about.

In terms of books, C# 3.0 in a Nutshell is very good. If you're really not a console kind of person, Head First C# may be up your street - it's not my preferred style, but many other people like it. However, make sure you get the latest printing, as lots of errors have been corrected.