Programming Microsoft ASP.NET 2.0 core reference

Dino Esposito

Mentioned 67

Build your expertise as you move beyond the basics—and delve into the core topics of programming with ASP.NET 2.0. Useful to both experienced developers and those developing new skills, this ultimate reference is packed with expert guidance, hands-on programming instruction, and practical examples to help you advance your mastery of developing applications for the Web. Discover how to: Author rich, visually consistent pages and manage layout with themes and Master pages Create personalized pages that persist user preferences Retrieve, modify, and manage data with Microsoft ADO.NET Configure the HTTP pipeline to serve ASP.NET 2.0 pages Control program flow by tracing and handling exceptions Design caching layers and learn state management techniques to optimize application performance Manage users with membership control, registration, and authentication capabilities Build real-world data access layers using common design patterns Use custom collections with data source controls Learn the internals of grid controls PLUS—Get code samples on the Web

More on Amazon.com

Mentioned in questions and answers.

Example (note the case):

string s = "Hello world!";
String S = "Hello world!";

What are the guidelines for the use of each? And what are the differences?

The best answer I have ever heard about using the provided type aliases in C# comes from Jeffrey Richter in his book CLR Via C#. Here are his 3 reasons:

  • I've seen a number of developers confused, not knowing whether to use string or String in their code. Because in C# the string (a keyword) maps exactly to System.String (an FCL type), there is no difference and either can be used.
  • In C#, long maps to System.Int64, but in a different programming language, long could map to an Int16 or Int32. In fact, C++/CLI does in fact treat long as an Int32. Someone reading source code in one language could easily misinterpret the code's intention if he or she were used to programming in a different programming language. In fact, most languages won't even treat long as a keyword and won't compile code that uses it.
  • The FCL has many methods that have type names as part of their method names. For example, the BinaryReader type offers methods such as ReadBoolean, ReadInt32, ReadSingle, and so on, and the System.Convert type offers methods such as ToBoolean, ToInt32, ToSingle, and so on. Although it's legal to write the following code, the line with float feels very unnatural to me, and it's not obvious that the line is correct:
BinaryReader br = new BinaryReader(...);
float val  = br.ReadSingle(); // Ok, but feels unnatural
Single val = br.ReadSingle(); // OK and feels good

So there you have it. I think these are all really good points. I however, don't find myself using Jeffrey's advice in my own code. Maybe I am too stuck in my C# world but I end up trying to make my code look like the framework code.

This came to my mind after I learned the following from this question:

where T : struct

We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.

Some of us even mastered the stuff like Generics, anonymous types, lambdas, LINQ, ...

But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?

Here are the revealed features so far:


Keywords

Attributes

Syntax

Language Features

Visual Studio Features

Framework

Methods and Properties

Tips & Tricks

  • Nice method for event handlers by Andreas H.R. Nilsson
  • Uppercase comparisons by John
  • Access anonymous types without reflection by dp
  • A quick way to lazily instantiate collection properties by Will
  • JavaScript-like anonymous inline-functions by roosteronacid

Other

I found that only few developers know about this feature.

If you need a method that works with a value-type variable via some interface (implemented by this value type), it's easy to avoid boxing during the method call.

Example code:

using System;
using System.Collections;

interface IFoo {
    void Foo();
}
struct MyStructure : IFoo {
    public void Foo() {
    }
}
public static class Program {
    static void MethodDoesNotBoxArguments<T>(T t) where T : IFoo {
        t.Foo();
    }
    static void Main(string[] args) {
        MyStructure s = new MyStructure();
        MethodThatDoesNotBoxArguments(s);
    }
}

IL code doesn't contain any box instructions:

.method private hidebysig static void  MethodDoesNotBoxArguments<(IFoo) T>(!!T t) cil managed
{
  // Code size       14 (0xe)
  .maxstack  8
  IL_0000:  ldarga.s   t
  IL_0002:  constrained. !!T
  IL_0008:  callvirt   instance void IFoo::Foo()
  IL_000d:  ret
} // end of method Program::MethodDoesNotBoxArguments

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       15 (0xf)
  .maxstack  1
  .locals init ([0] valuetype MyStructure s)
  IL_0000:  ldloca.s   s
  IL_0002:  initobj    MyStructure
  IL_0008:  ldloc.0
  IL_0009:  call       void Program::MethodDoesNotBoxArguments<valuetype MyStructure>(!!0)
  IL_000e:  ret
} // end of method Program::Main

See Richter, J. CLR via C#, 2nd edition, chapter 14: Interfaces, section about Generics and Interface Constraints.

See also my answer to another question.

From CLR via C#:

When normalizing strings, it is highly recommended that you use ToUpperInvariant instead of ToLowerInvariant because Microsoft has optimized the code for performing uppercase comparisons.

I remember one time my coworker always changed strings to uppercase before comparing. I've always wondered why he does that because I feel it's more "natural" to convert to lowercase first. After reading the book now I know why.

Just this - How do you add a timer to a C# console application? It would be great if you could supply some example coding.

Use the System.Threading.Timer class.

System.Windows.Forms.Timer is designed primarily for use in a single thread usually the Windows Forms UI thread.

There is also a System.Timers class added early on in the development of the .NET framework. However it is generally recommended to use the System.Threading.Timer class instead as this is just a wrapper around System.Threading.Timer anyway.

It is also recommended to always use a static (shared in VB.NET) System.Threading.Timer if you are developing a Windows Service and require a timer to run periodically. This will avoid possibly premature garbage collection of your timer object.

Here's an example of a timer in a console application:

using System; 
using System.Threading; 
public static class Program 
{ 
    public static void Main() 
    { 
       Console.WriteLine("Main thread: starting a timer"); 
       Timer t = new Timer(ComputeBoundOp, 5, 0, 2000); 
       Console.WriteLine("Main thread: Doing other work here...");
       Thread.Sleep(10000); // Simulating other work (10 seconds)
       t.Dispose(); // Cancel the timer now
    }
    // This method's signature must match the TimerCallback delegate
    private static void ComputeBoundOp(Object state) 
    { 
       // This method is executed by a thread pool thread 
       Console.WriteLine("In ComputeBoundOp: state={0}", state); 
       Thread.Sleep(1000); // Simulates other work (1 second)
       // When this method returns, the thread goes back 
       // to the pool and waits for another task 
    }
}

From the book CLR Via C# by Jeff Richter. By the way this book describes the rationale behind the 3 types of timers in Chapter 23, highly recommended.

I come from a C++ background and I've been working with C# for about a year. Like many others I'm flummoxed as to why deterministic resource management is not built-in to the language. Instead of deterministic destructors we have the dispose pattern. People start to wonder whether spreading the IDisposable cancer through their code is worth the effort.

In my C++-biased brain it seems like using reference-counted smart pointers with deterministic destructors is a major step up from a garbage collector that requires you to implement IDisposable and call dispose to clean up your non-memory resources. Admittedly, I'm not very smart... so I'm asking this purely from a desire to better understand why things are the way they are.

What if C# were modified such that:

Objects are reference counted. When an object's reference count goes to zero, a resource cleanup method is called deterministically on the object, then the object is marked for garbage collection. Garbage collection occurs at some non-deterministic time in the future at which point memory is reclaimed. In this scenario you don't have to implement IDisposable or remember to call Dispose. You just implement the resource cleanup function if you have non-memory resources to release.

  • Why is that a bad idea?
  • Would that defeat the purpose of the garbage collector?
  • Would it be feasible to implement such a thing?

EDIT: From the comments so far, this is a bad idea because

  1. GC is faster without reference counting
  2. problem of dealing with cycles in the object graph

I think number one is valid, but number two is easy to deal with using weak references.

So does the speed optimization outweigh the cons that you:

  1. may not free a non-memory resource in a timely manner
  2. might free a non-memory resource too soon

If your resource cleanup mechanism is deterministic and built-in to the language you can eliminate those possibilities.

The garbage collector does not require you to write a Dispose method for every class/type that you define. You only define one when you need to explicitly do something to cleanup ; when you have explicitly allocated native resources. Most of the time, the GC just reclaims memory even if you only do something like new() up an object.

The GC does reference counting - however it does it in a different way by finding which objects are 'reachable' (Ref Count > 0) every time it does a collection... it just doesn't do it in a integer counter way. . Unreachable objects are collected (Ref Count = 0). This way the runtime doesn't have to do housekeeping/updating tables everytime an object is assigned or released... should be faster.

The only major difference between C++ (deterministic) and C# (non-deterministic) is when the object would be cleaned up. You can't predict the exact moment an object would be collected in C#.

Umpteenth plug: I'd recommend reading Jeffrey Richter's standup chapter on the GC in CLR via C# in case you're really interested in how the GC works.

I've been an admirer of Juval Lowy's teaching and guidance in .NET development for a number of years. He's also written one of my favorite books: Programming .NET Components.

However on a recent DotNet Rocks podcast (Jan 2010) in discussing WCF/COM and .NET, he made some comments that greatly surprised me:

Juval Löwy: ..... in .NET, lo and behold, every class here is a COM object. We know that. In fact, it's much more than COM because we've got the git compiling, we've got garbage collection, we've got the Security Stack....

Carl Franklin: Well, you should clarify that though. I mean, every object is not a COM object. Every object has the capabilities that a COM object does, but the .NET Framework isn't a COM library.

Juval Löwy: No, no. First of all .NET is actually built on top of COM. It's all COM underneath.

Then, after Carl Franklin asks for clarification on this comment:

Carl Franklin: Yeah, I get that. My question was is .NET built on COM?

Juval Löwy: Of course, it all COM underneath.

Carl Franklin: No. I know it's intertwined and it's required, but when you new up a .NET object you're not creating a COM object.

Juval Löwy: You're creating a .NET object, but all I'm saying is that .NET is built underneath. It's all C++ and COM.

Carl Franklin: It is C++ but you're not registering a COM object through the COM interface. It isn't all that stuff unless you specifically do that.

Juval Löwy: But some of the stuff is using COM underneath, but that's beside the point. Forget about how it's made.

How do you read these comments?

While I understand (and have confirmed) that some of the System assemblies are written in unmanaged C++, is it also valid to say that they are "all COM underneath"?

I was under the assumption it is perfectly possible to write .NET CLI compliant C++ assemblies that have absolutely nothing to do with COM / ATL / ActiveX?

Here is the PDF transcript for the podcast in question. See Page 7.

Dave Markle's answer reminded me of something Jeff Richter said in CLR Via C#.

(Chapter 21, CLR Hosting and AppDomains)

The .NET Framework runs on top of Microsoft Windows. This means that the .NET Framework must be built using technologies that Windows can interface with. For starters, all managed module and assembly files must use the Windows portable executable (PE) file format and be either a Windows EXE file or a dynamic-link library (DLL).

When developing the CLR, Microsoft implemented it as a COM server contained inside a DLL; that is, Microsoft defined a standard COM interface for the CLR and assigned GUIDs to this interface and the COM server. When you install the .NET Framework, the COM server representing the CLR is registered in the Windows registry just as any other COM server. If you want more information about this topic, refer to the MSCorEE.h C++ header file that ships with the .NET Framework SDK. This header file defines the GUIDs and the unmanaged ICLRRuntimeHost interface definition.

I am guessing that this is pretty close to explaining Juval's comments.

Alex DeLarge also makes a good point in another answer that there is a difference between the implementation of the CLR itself and the Base Class Library assemblies.

I was certainly focusing on the BCL assemblies (Juval: "every clss here is a COM object") and application assemblies so this may be the cause of the confusion.

A very open question. I've been programming in C# for the past 5 months doing small projects that I completed successfully.

Today I went to an interview for a C# role. The 1st question was 'Tell me about boxing'. Given my experience I had no idea what the guy meant. Needless to say the interview didn't go that well. Others questions were 'why isn't it recommended to use an ArrayList of int', 'tell me what you know about threading', etc.

I don't really want this to happen again so I'm planning to spend some time reading (and practising) more on C#. I understand that the best way of learning is by coding but coding wouldn't have really helped me answer the question about 'boxing' for example.

I'm not asking you to answer the above technical questions. In fact, I know now their answer as I went straight to Google after the interview and it's how I realised that my C# knowledge is somewhat limited.

My question is: in your opinion, which knowledge should any C# developer have? Ideally it would be better if you could categorize it (Basic knowledge anyone should have without exception, Advanced knowledge, Expert knowledge etc). No need to go into details. Doing research on whatever you list will be a good exercise for me.

This is something I have been pondering myself a lot lately. Using C# plenty but not sure what I am missing.

I ordered

Microsoft® .NET Framework Application Development Foundation

Which covers a lot of ground related to C#

Also looking at C# in Depth

Read some of this already. Has some great information from a high quality author.

In depth is on sale too via Jon Skeet's blog

Five months without any knowledge of boxing? My dear, dear, boy. I would hesitate to be in your position. Why, I remember those halcyon days when I, like you now, similarly lacked some of the basic knowledge of the tools of my craft. But, do not despair, lad! You have time and the desire to learn. Let us, forthwith, dispense some knowledge that you may use to your future benefit! Huzzah!

Read CLR Via C# cover to cover. Grab a Linq book (can't recommend any off the top of my head). Write an application using WPF (for the xaml). Those three things I think will give you the biggest bang for your buck right now.

I've jumped into the C# bandwagon and was wondering if there's an equivalent of Joshua Bloch's Effective Java for the C# world.

I've already being able to apply some Java knowledge to C# given their similarity but I'm interested in knowledge to make the most effective use of C# specific features. For example, Generics are not implemented equally in Java and C#, so it's not clear to me if the Java Generic "techniques" will work in C# as well.

I'm mostly interested in C# 3.0. That is (of course) unless you guys think I would benefit for looking into versions 1 and 2 features.

I think Framework Design Guidelines is the closest. While I don't think it's comparable to Effective Java in terms of depth, I haven't read found any better book in the same category.

C# in Depth is great, but it focuses more on the language than design issues in .NET. Therefore, I wouldn't put it in the same category with Effective Java.

alt text

Effective C# and More Effective C# by Bill Wagner. The second book deals with C# 2 and 3.

Either here and here on Amazon.com

or here and here on Amazon.co.uk

There's a new version of Effective C# (Amazon UK) that covers C# 4.0.

Beaten to it by Andy, but I was looking up the links.

Jon Skeet's C# In Depth is a favorite among StackOverflow users.

C# In Depth

Since you want something in the same line of Effective Java the following two books are very similar:

Effective C#

More Effective C#

Jon Skeet's C# In Depth is also worth mentioning.

How about Effective C#?

There are two books Effective C# and More Effective C# by Bill Wagner that are similar to Effective Java.

I found CLR Via C#, by Jeffery Richter, to be very good. It discusses the CLR and framework in some depth and gives you a greater understanding of how to use various feature along with potential pitfalls.

Let's have an object created in a getter like this :

public class Class1
{
       public string Id { get; set; }
       public string Oz { get; set; }
       public string Poznamka { get; set; }

       public Object object
       {
             get
             {
                  // maybe some more code
                  return new Object { Id = Id, poznamla = Poznamka, Oz = OZ };
             }
        }
 }

Or should I rather create a Method that will create and return the object ?

Properties look like fields but they are methods. This has been known to cause a phenomenal amount of confusion. When a programmer sees code that appears to be accessing a field, there are many assumptions that the programmer makes that may not be true for a property.So there are some common properties design guidelines.

  1. Avoid returning different values from the property getter. If called multiple times in a row, a property method may return a different value each time; a field returns the same value each time.

  2. A property method may require additional memory or return a reference to something that is not actually part of the object's state, so modifying the returned object has no effect on the original object; querying a field always returns a reference to an object that is guaranteed to be part of the original object's state. Working with a property that returns a copy can be very confusing to developers, and this characteristic is frequently not documented.

  3. Consider that a property cannot be passed as an out or ref parameter to a method; a field can.

  4. Avoid long running property getters. A property method can take a long time to execute; field access always completes immediately.

  5. Avoid throwing exceptions from getters.

  6. Do preserve previous values if a property setter throws an exception

  7. Avoid observable side effects.

  8. Allow properties to be set in any order even if this results in a temporary invalid state of objects.

Sources

"CLR via C#", Jeffrey Richter. Chapter 9. Defining Properties Intelligently

"Framework Design Guidelines" 2nd edition, Brad Abrams, Krzysztof Cwalina, Chapter 5.2 Property Design

I have some 5+ years' background in C++/Unix development. I have been trying my hand at C#/.Net/WPF based software development for some time now. I am at a stage where I can write functioning applications fluently, but am not sure how to take my skills to the next level.

So, my question(s) to you all, especially to those who are experienced in C#/.Net/WPF:

  • What are the component skills and knowledge that an expert developer on this platform should have?

  • What technology-specific books would you expect a would-be expert to have read?

  • What other deliberate steps can I take to become really good at application development using C#/.Net/WPF?

Many thanks in advance! I would be especially grateful for comprehensive answers - I'm pretty sure many other developers have similar questions.

I really like WPF in Action and Programming .NET Components is essential reading for any .NET developer.

Learn how the C# language and .NET runtime work by reading CLR via C#.

My team has worked in C# for the past 5 years. Typically, experienced C++ programmers take a week or two to become fully functional in C#. I've even seen some do it almost instantly, after sitting with them one morning, showing them our code, and explaning the basics of the language that differ from C++. But that's not how I recommend you do it.

I recommend you do this:

Read a C# book: My pick would be Programming C# by Jesse Liberty. Important chapters are the language itself and the basics of the .NET framework libraries. The .NET Framework is huge, so you don't have to know everything in detail. You can skip through (or skim) the Windows Forms chapters. Windows Forms is so different from WPF that it won't be useful to you if you are planning on only doing WPF.

alt text

Read a WPF book: The best book I read so far is Windows Presentation Foundation Unleashed by Adam Nathan. WPF has a steep learning curve compared to Windows Forms, even for experienced C#/WinForms programmers. It has a lot of complex elements to understand like XAML, dependency properties, bindings, templates, animation, resources, etc. This book teaches you the basics gradually and is easy to read and understand. And it's in full color!

alt text

Read about the Model-View-ViewModel pattern: I haven't found a good book on that yet, but it's been very important for me to make my WPF applications more simple and manageable. My favorite material to learn about MVVM is this one hour presentation by Jason Dolinger. He builds a WPF application from scratch using no particular pattern, and step by step, migrates it to the MVVM pattern.

I would add unit testing, TDD, and mocking frameworks to your list of things to know.

I have "The Art of Unit Testing" and found it helpful.

Assembly in .net Framework is, as I understand, intermediate language file + some metadata, manifest and maybe something else.

CLR translates an assembly to the machine code, which can be executed on the given local machine.

That means that assembly shouldn't be executable by the machine before being processed by CLR. If it's so, then why does it have .exe extension, which is executable on Windows machines?

Since Windows needs to create a process and the first thing .exe will do is to host CLR by loading mscoree.

From CLR via C#:

After Windows has examined the EXE file's header to determine whether to create a 32-bit process, a 64-bit process, or a WoW64 process, Windows loads the x86, x64, or IA64 version of MSCorEE.dll into the process's address space. On an x86 version of Windows, the x86 version of MSCorEE.dll can be found in the C:\Windows\System32 directory. On an x64 or IA64 version of Windows, the x86 version of MSCorEE.dll can be found in the C:\Windows\ SysWow64 directory, whereas the 64-bit version (x64 or IA64) can be found in the C:\Windows\System32 directory (for backward compatibility reasons). Then, the process' primary thread calls a method defined inside MSCorEE.dll. This method initializes the CLR, loads the EXE assembly, and then calls its entry point method (Main). At this point, the managed application is up and running.

I work for a research department in a big company and we use .Net platform to build our prototypes (That means the product team always reproduce our work if the prototype is 'useful'.).

We also hire interns for our projects. Some of the interns are mainly doing research, thus code less. But anyway, interns need to do some coding in C#, or F# if they can. Most of them don't have any C# experience before. They are senior undergrads or grads, and usually know some Java and C++. But they usually have not received any formal training in industry-quality programming.

The hard problem is to teach them C#/.Net fast as they should focus on their research problems during a 3 or 6 months internship. Also they really need to know some good C# practice, otherwise the codebase during their internship is not reuseable after the internship.

My way of learning C# is different from others (I learned F# first and then read CLR via C# and Effective Java from cover to cover. ) So I'd like to consult experienced C# users to suggest a short-term (say, 2 or 3 days) C# tutorial. Thanks a lot!

Either ask them to buy, or buy for them, the following two books:

Essential C# 4.0 and C# 4.0 in a Nutshell

If you really care about their style, as you say you do, also get them:

Effective C# 2nd ed.

Given this set and assuming they already know how to program in general (e.g., Java/C++), they can get productive in a matter of weeks. You can use the Effective C# guidelines to help promote manageable code, at least at a low level.

I'm from the world of C# originally, and I'm learning C++. I've been wondering about get and set functions in C++. In C# usage of these are quite popular, and tools like Visual Studio promote usage by making them very easy and quick to implement. However, this doesn't seem to be the case in the C++ world.

Here's the C# 2.0 code:

public class Foo
{
    private string bar;

    public string Bar
    {
        get { return bar; }
        set { bar = value; }
    }
}

Or, in C# 3.0:

public class Foo { get; set; }

May people will say, well whats the point in that? Why not just create a public field and then make it a property later if you need to; honestly, I'm actually not sure. I just do it out of good practice because I've seen it done so many times.

Now because I'm so used to doing it, I feel like I should carry over the habit to my C++ code, but is this really necessary? I don't see it done as often as with C#.

Anyway, here's the C++ from what I gather:

class Foo
{
public:
    std::string GetBar() const; // Thanks for the tip Earwicker.
    void SetBar(std::string bar);
private:
    std::string bar;
}

const std::string Foo::GetBar()
{
    return bar;
}

void Foo::SetBar(std::string bar)
{
    // Also, I always wonder if using 'this->' is good practice.
    this->bar = bar;
}

Now, to me that seems like a whole lot of leg work; considering using Visual Studio's tools the C# implementation would take literally seconds to implement, and the C++ took me a lot longer to type - I feel its not worth the effort, especially when the alternative is 5 lines long:

class Foo
{
public:
    std::string Bar;
}

From what I gather, these are the advantages:

  • You can change implementation details for the get and set functions, so instead of returning a private field you can return something more interesting.
  • You can remove a get/set later on and make it read/write only (but for a public facing interface, this seems, not good).

And the disadvantages:

  • Takes ages to type, is this really worth the effort? Generally speaking. In some cases, the advantages make it worth the effort, but I mean, speaking in terms of "good practice", is it?

Answer:

Why did I choose the answer with less votes? I was actually very close to choosing veefu's answer; however my personal opinion (which is apparently controversial), is that the answer over egged the pudding.

The answer I chose, on the other hand, seems to argue both sides; I think getters and setters are evil if used excessively (by that I mean, when it's not necessary and would break the business model), but why shouldn't we have a function called GetBalance()?

Surely this would be far more versatile than PrintBalance(); what if I wanted to show it to the user in another way than as the class wanted me to? Now, in some sense GetBalance() may not be relevant enough to argue that "getters and setters are good" because it doesn't (or maybe, shouldn't) have an accompanying setter, and speaking of which, a function called SetBalance(float f) could be bad (in my opinion) because it would imply to the implementer of the function that the account must be manipulated out side of the class, which is not a good thing.

The compiler will emit set_ and get_ if you define a property, so it's really just save some typing.

This has been an interesting discussion. This is something from my favorite book "CLR via C#".

Here is what I quoted.

Personally, I don't like properties and I wish that they were not supported in the Microsoftm.NET Framework and its programming languages. The reason is because properties look like fields but they are methods. This has been known to cause a phenomenal amount of confu-sion. When a programmer sees code that appears to be accessing a field, there are many assumptions that the programmer makes that may not be true for a property. For example,

  • A property may be read-only or write-only; field access is always
    readable and writable. If you define
    a property, it is best to offer both
    get and set accessor methods.
  • A property method may throw an exception; field access never throws
    an exception.

  • A property cannot be passed as an out or ref parameter to a method; a field can.

  • A property method can take a long time to execute; field access always
    completes imme- diately. A common
    reason to use properties is to
    perform thread synchronization, which can stop the thread forever, and
    therefore, a property should not be
    used if thread synchro- nization is
    required. In that situation, a method is preferred. Also, if your class can be accessed remotely (for example,
    your class is derived from
    System.MashalByRefObject), calling
    the property method will be very
    slow, and therefore, a method is
    preferred to a property. In my
    opinion, classes derived from
    MarshalByRefObject should never use
    properties.

  • If called multiple times in a row, a property method may return
    a different value each time; a
    field returns the same value each
    time. The System.DateTime class has a read- only Now property that returns
    the current date and time. Each time you query this property, it will
    return a different value. This is a
    mistake, and Microsoft wishes that
    they could fix the class by making
    Now a method instead of a property.

  • A property method may cause observable side effects; field access never does. In other words, a user of a type should be able to set various
    properties defined by a type in any
    order he or she chooses without
    noticing any different behavior in
    the type.

  • A property method may require additional memory or return a
    reference to something that is not
    actually part of the object's state, so modifying the returned object has
    no effect on the original object;
    querying a field always returns a
    reference to an object that is
    guaranteed to be part of the original object's state. Working with a
    property that returns a copy can be
    very confusing to developers, and
    this characteristic is frequently not documented.

This is an open-ended question. What approaches should I consider?

Your first step is to find and understand the parallelism in your problem. It is really easy to write multi-threaded code that performs no better than the single-threaded code it replaces. "Patterns for Parallel Programming" (Amazon) is a great introduction to the key concepts.

Once you have a workable design, start reading the articles in the "Concurrency" topic in the MSDN Magazine archives (link), particularly anything written by Jeff Richter. Those will give you the nuts and bolts stuff on the threading constructs specific to Windows and .NET. (The multi-threading section in Richter's "CLR via C# (Amazon)is short, but very insightful - highly recommended.)

What is the behind-the-scenes difference between 'int?' and 'int'? Is 'int?' a somehow a reference type?

For one of the better "behind the scenes" discussions about Nullable types you should look at CLR Via C# by Jeffrey Richter.

The whole of Chapter 18 is devoted to discussing in detail Nullable types. This book is also excellent for many other areas of the .NET CLR internals.

Possible Duplicate:
Difference between lock(locker) and lock(variable_which_I_am_using)

In all of the "thread-safe" code examples i've seen, they lock on a separate dummy object. Why cant locks be directly performed on the data in question?

Jeff Richter (author of CLR Via C#) explains why in this article on Safe Thread Synchronization.

Specifically, in that article the section "Why the Great Idea isn't So Great" answers your question.

It's actually a chapter from the book CLR Via C#.

In summary, having a private object as the "synclock" object allows your class to encapsulate and control any locking your class needs. Therefore regardless of how many clients use your class, locking is performed consistently and correctly.

I'm a Java/C++ developer that never spent time in learning C# and the relative .NET foundation.

Then I learned OCaml because I had to use it for my master thesis so I heard about F# and wondered: will F# allows me to use easily the .NET API to build fully featured applications (that may involve GUIs, sockets, whatever) without any problem?

I ask this because it seems that F# syntax and concepts are quite similar to OCaml and when they are different it's just because a more OOP approach is used so Java knowledge would help me in filling that holes.. if F# is able to use same resources as C# without the need to learn C# syntax I would really consider that.. does it worth trying?

Apart from that, are the books available on Amazon for F# (mainly one book from O'Reilly and 3-4 books from Apress) good to learn advanced techniques? Because now I'm quite fond of functional programming but never worked on .NET platform so I really don't know where to start from.

Thanks in advance

In my experience, you need some C# to learn F#, especially for the .Net part.

Similar to your situation, I didn't know any .Net and C# before learning F#. The first hard part for me is asynchronous IO programming. I get a full understanding of it until I read the async chapter of CLR via C#. And I soon found that what bited me was not computation expression/monads, it is .NET. Then I continue to read CLR via C#, e.g. I know that in .Net 1d array is efficient, however 2d array is not that efficient. I also get to know delegates and events in .Net.

.Net is imperative. C# is the mother tone for .Net. IMHO, learning C# (at least reading C#) is required for an F# programmer.

I'm re-reading CLR via C# right now and have some questions about garbage collection in .NET. In the book, after Generation 0 is filled, garbage collection starts and moves all outstanding object references to the Generation 1.

The same happens when the Generation 1 is filled. But what happens when second generation is filled? There are no other generations to move references. Is the size of Generation 2 expanded by the CLR?

Yes, it will expand the size of Generation 2 if it can. If there is no more space available you will get an OutOfMemoryException.

When a value type is boxed, it is placed inside an untyped reference object. So what causes the invalid cast exception here?

long l = 1;
object obj = (object)l;
double d = (double)obj;

No, it's not placed in an untyped object. For each value type, there's a boxed reference type in the CLR. So you'd have something like:

public class BoxedInt32 // Not the actual name
{
    private readonly int value;
    public BoxedInt32(int value)
    {
        this.value = value;
    }
}

That boxed type isn't directly accessible in C#, although it is in C++/CLI. Obviously that knows the original type. So in C# you have to have a compile-time type of object for the variable but that doesn't mean that's the actual type of the object.

See the ECMA CLI spec or CLR via C# for more details.

Assuming all goes well and I get employed by the company I am about to interview with I will probably need to learn .NET and C#

I already know PHP, Python, Java and some C (Pointers and Memory Management are not so good) so I'm going to be able to do it if I can find a good tutorial to cover the key parts of it, does anybody have a link to a good tutorial for it or better yet, for someone switching from one of those languages to .NET?

There are some good books for developers with Java background:

Here are one of the best books on C#:

  • C# 3.0 Unleashed: With the .NET Framework 3.5
  • Head First C#
  • Programming C# 3.0
  • C# 3.0 Design Patterns

One book that I consider as a must read is "Framework Design Guidelines" It really helps to understand how and why .NET was designed,

Buy and read CLR Via C# from cover to cover. This is THE book on .NET, covering the Common Language Runtime and a good deal of the syntax of C#. Its a heavy book, but reads well. Just skip the first few chapters, saving them for when you've completed reading the rest of the book.

Keep in mind, the book covers .NET 2.0. The current CLR is in version 2.0; the framework is now at 3.5. So the book may seem to be out of date, however it isn't. You will need to learn Linq (which supercedes ADO), WPF (which supercedes Windows Forms) and WCF (which supercedes... a jumbled mishmash of different communication methods) seperately.

In a form, compare

BeginInvoke (new Action (() => {
    MessageBox.Show ());
}));

with

Invoke (new Action (() => {
    MessageBox.Show ());
}));

What is the difference, and when should I use one over the other? How is the behavior affected by the message pump of the MessageBox?

I did some testing and found that both methods block the UI.

The only difference is that Invoke is actually called instantly while BeginInvoke takes a (very short) time until the code is run. This is to be expected.

While most of the answers are technically correct, they don't ask the obvious question.

Why do you want to wrap your MessageBox() calls in Invoke/BeginOnvoke in the first place?

There is simply no benefit in using BeginInvoke or Invoke in this situation, as Jeff explained.

It sounds like you're gettng confused between using Invoke/BeginInvoke on a windows form/control in a multi-threaded situation, and using Invoke/BeginInvoke on a delegate instance (ie the Asynchornous Programming Model).

This is easy to do as the names are obviously identical, however the scenarios you would use them and their behaviour is different.

The book CLR Via C# gives a good explanation of both types of Invoke/BeginInvoke.

I've been programming in C and C++ in Linux for around 3 years, and recently have been interested in developing commercial software for businesses. Let's say I've found a niche where I think I could be successful, but that they only use Windows. I have no experience whatsoever with the Windows API, however. I have a few questions:

Should I learn .NET?

Do I need to learn C# in order to use .NET, or can I stick with C++?

What is the sentiment about compiling using GCC under Cygwin with the --no-cygwin option? I'm interested in portability, and I'm worried that if I start writing for VC++, I might get bound to Windows.

Where is a good place to do my essential reading?

What else can you tell me about transitioning from Linux to Windows programming?

no. dont learn .NET - learn C#.. its like the anything goes playground. once you get the hang of it.. you will be able to finish projects in 1/10th the time..

but with C#/.NET you learn bad habits. i am now back in C++. i had C++ 12years, then C# 5 years, now C++ 6 months.

although it does take around 6 times longer to complete projects... (6 months vs 1 month) , i feel that the C++ code has an artistic feel.. while the C# code is generic. like BestBuy.

i am totally anti C++/CLI or whatever its called. if you need to get down to the CLR level.. run, dont walk back to C++.. or you'll end up spending all your time working around some arbitrary C# design "feature" like event synchronization..

my next destination may be .NET Powershell to manage my C++ server applications.

I did Unix to Windows move around 10 years ago.. i tried going back to FreeBSD or Linux... I used to love vi.. but VS is by far the best IDE by far. just get vs2010 pro + reshaper and read these 2 books. the first one is core C# but its .NET 2.0 , which is good.. because its easiest to start writing C++ style code anyways. the next book will last you years.

http://www.amazon.com/2-0-Practical-Guide-Programmers-Guides/dp/0121674517

http://www.amazon.com/gp/reader/0735627045/ref=sib_dp_pt#reader-link

hope this helps.

also. no reason NOT to write portal c++ code in the year 2012. cmake + VS2010 + boost + crossroads-io

I faced exactly the same questions and I am so happy I tried .NET. I hope this info can help you:

Should I learn .NET?

I would highly recomment it.

Do I need to learn C# in order to use .NET, or can I stick with C++?

You can stick with C++ but I am sure you will love to learn C#, please try it. You will be able to mix them too. The main challenge with .NET is to learn all the libraries that are out there to help you out (so you do not need to reinvent the wheel). Use msdn often and try to get a map of the fundamental classes and assemblies.

It is a fun experience if you come from C++ you should not have major problems.

Where is a good place to do my essential reading?

I would start with something light, check the free Visual Studio tools, software and examples here, go to the MSDN documentation and compile some of the examples in MSDN (how to access files,...). As you can see you will find C# and C++ examples side by side.

Then of course books like C# via CLR will eventually need to be read.

Portability

Be sure you run your code in Mono and multiple platforms.

Future investment

Investing on learning the .NET framework will pay back. Today is costly to learn all the new tools out there, with .NET you know you can evolve. New features and languages appear but the fundamental classes remain so your time/effort investment is more under control.

I want to do a project where I build a database-aware program with a front end using .NET with C#.

I am totally new to this language. Can anyone recommend a good resource? Perhaps an online PDF version of a book?

There are many awesome books for C# beginers. You can use "HeadFirst C#" or "Begining C#" to give a start. Once you get hands on practice on C#, then you can try "Illustrated C# 2008" and/or "Inside C#" books. These books does not cover all the features of C#, but these will give you detailed description of features of C#.

For C#:

  1. CLR via C#
  2. C# in depth from our own nice guy.

The MSDN "Writing Faster Managed Code: Know What Things Cost" is pretty nice, but it was written for CLR v1 in 2003. Is there an updated version of this somewhere?

I don't know of one that replaces that but the book CLR via C# will provide you with a lot of deep and relevant knowledge for how the CLR works and where it consumes a lot of time and resources.

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:

I'm learning C#. From what I know, you have to set things up correctly to have the garbage collector actually delete everything as it should be. I'm looking for wisdom learned over the years from you, the intelligent.

I'm coming from a C++ background and am VERY used to code-smells and development patterns. I want to learn what code-smells are like in C#. Give me advice!

What are the best ways to get things deleted?

How can you figure out when you have "memory leaks"?


Edit: I am trying to develop a punch-list of "stuff to always do for memory management"


Thanks, so much.

Others have already mentioned the importance of IDisposable, and some of the things to watch out for in your code.

I wanted to suggest some additional resources; I found the following invaluable when learning the details of .NET GC and how to trouble-shoot memory issues in .NET applications.

CLR via C# by Jeffrey Richter is an excellent book. Worth the purchase price just for the chapter on GC and memory.

This blog (by a Microsoft "ASP.NET Escalation Engineer") is often my go-to source for tips and tricks for using WinDbg, SOS, and for spotting certain types of memory leaks. Tess even designed .NET debugging demos/labs which will walk you through common memory issues and how to recognize and solve them.

Debugging Tools for Windows (WinDbg, SOS, etc)

I want to start reading about multithreading and parallel computing in C# / .Net 4.0.

I understand the basics of multithreading so I'm looking for something that is going to provide more than just the basics. I'm also looking for something that is up to date with the changes in .Net 4.0.

Can you recommend a book?

Many thanks.

I suppose when it comes to anything in C#, I would recommend CLR via C#. It has got two chapters on threading-parallelprocessing which is a must read.

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.

What are the advantages of understanding CIL?

Do you have to know assembly to understand it? The code in these files looks similar.

How do I learn more about it? Any books about it like Jon Skeet's C# book?

I found these books useful when learning IL and about the CLR:

Just reading through them will give you lots of information.

(I've also heard CLR via C# is really good, but haven't read it myself.)

Understanding IL and the CLR will give you a leg up when you run into a problem. (A leaky abstraction?) Although, these days with nice decompilers like Reflector, I don't find myself using ildasm as much.

Understanding assembly isn't necesarily required, but it would help. IL is actually pretty simple for the most part.

One example of where IL came in handy was determining exactly how exactly F# compiles certain constructs. Another is being able to use DynamicMethod and System.Reflection.Emit, which can open up some nice solutions in certain situations.

When I was learning .NET I saw it as a platform that runs my .NET programs which has its own Stack & Heap.

But now after learning more about things, I see a .NET application as just like any other C/C++ native application. It is in Portable Executable (PE) file format with new data directory & .text section is filled with MSIL code instead of machine code. The only difference is few DLLs (which are considered as .NET platform) (like any other Dll dependency) are loaded.

I guess at the very entry point there is some machine code which calls into the loaded DLL(.net platform) and functions of those DLL read the MSIL from .text section (segment to be more correct) and generate equivalent machine code and put it in some kind of buffer (I don't know which area would it be it. I cannot be .text & .data as they are readonly. will they be stack or heap?). Then make the EIP point to this buffer of instructions. Last few instructions again call back into DLLs to repeat the process for rest of MSIL.

As of Managed Heap & Managed Stack they are just some portion of the processes heap & stack. its just that few functions (referred to as GC) will keep track of the memory allocations & deallocations from this portions of memory.

I like this realistic view. I don't know how far I'm true. I'm just guessing these things. Please correct me & tell me more about this. How far will is it similar to this view? Where can I learn more about .NET platform from this point of view?

Lately I have been reading Pro C# 2008 and the .NET 3.5 Platform (there's now a VS2010/.NET 4.0 version, too), and it does a great job explaining how the .NET bytecode works on the back-end, and how you can learn about what's really being called by using the reflector, etc. It's dense and long (and sometimes more info than I wanted), but it's good informative reading.

CLR via C# describes some internal .NET things, including PE load process and hosting of CLR in your own process.

For CLR check : CLR via C#.

It is really a great book especially if you are interested in "low level" .NET/CLR.

For JVM check : Java Virtual Machine

System.Array serves as the base class for all arrays in the Common Language Runtime (CLR). According to this article:

For each concrete array type, [the] runtime adds three special methods: Get/Set/Address.

and indeed if I disassemble this C# code,

int[,] x = new int[1024,1024];
x[0,0] = 1;
x[1,1] = 2;
x[2,2] = 3;
Console.WriteLine(x[0,0]);
Console.WriteLine(x[1,1]);
Console.WriteLine(x[2,2]);

into CIL I get,

IL_0000:  ldc.i4     0x400
IL_0005:  ldc.i4     0x400
IL_000a:  newobj     instance void int32[0...,0...]::.ctor(int32,
                                                         int32)
IL_000f:  stloc.0
IL_0010:  ldloc.0
IL_0011:  ldc.i4.0
IL_0012:  ldc.i4.0
IL_0013:  ldc.i4.1
IL_0014:  call       instance void int32[0...,0...]::Set(int32,
                                                       int32,
                                                       int32)
IL_0019:  ldloc.0
IL_001a:  ldc.i4.1
IL_001b:  ldc.i4.1
IL_001c:  ldc.i4.2
IL_001d:  call       instance void int32[0...,0...]::Set(int32,
                                                       int32,
                                                       int32)
IL_0022:  ldloc.0
IL_0023:  ldc.i4.2
IL_0024:  ldc.i4.2
IL_0025:  ldc.i4.3
IL_0026:  call       instance void int32[0...,0...]::Set(int32,
                                                       int32,
                                                       int32)
IL_002b:  ldloc.0
IL_002c:  ldc.i4.0
IL_002d:  ldc.i4.0
IL_002e:  call       instance int32 int32[0...,0...]::Get(int32,
                                                        int32)
IL_0033:  call       void [mscorlib]System.Console::WriteLine(int32)
IL_0038:  ldloc.0
IL_0039:  ldc.i4.1
IL_003a:  ldc.i4.1
IL_003b:  call       instance int32 int32[0...,0...]::Get(int32,
                                                        int32)
IL_0040:  call       void [mscorlib]System.Console::WriteLine(int32)
IL_0045:  ldloc.0
IL_0046:  ldc.i4.2
IL_0047:  ldc.i4.2
IL_0048:  call       instance int32 int32[0...,0...]::Get(int32,
                                                        int32)
IL_004d:  call       void [mscorlib]System.Console::WriteLine(int32)

where the calls to the aforementioned Get and Set methods can be clearly seen. It seems the arity of these methods is related to the dimensionality of the array, which is presumably why they are created by the runtime and are not pre-declared. I couldn't locate any information about these methods on MSDN and their simple names makes them resistant to Googling. I'm writing a compiler for a language which supports multidimensional arrays, so I'd like to find some official documentation about these methods, under what conditions I can expect them to exist and what I can expect their signatures to be.

In particular, I'd like to know whether its possible to get a MethodInfo object for Get or Set for use with Reflection.Emit without having to create an instance of the array with correct type and dimensionality on which to reflect, as is done in the linked example.

I'm not sure if it will address your very specific question but a great text on the subject (among others) is CLR via C#. It gets very in-depth for many of the topics you're interested in and spends a lot of time with the disassembler looking at the inner workings of many base .NET types including arrays. Definitely worth checking out.

Can you recommend a good series of articles or preferably a book on how to get started with threading in general and in C# in particular? I am primarily looking for the use of threads in console applications and in ASP.Net apps.

I understand only the very basics of threads and know that "here be dragons", so want to get a good grounding in it before I start using them.

Things I am curious about are things like the concept of having a threadpool, how you manage the size of it, how you choose for things to be queued until a thread is available vs forcing a new thread to start etc. Also, I understand that IIS has lots of built-in thread handling, so anything that explains how to work with threads in ASP.Net under IIS and how it differs from threading in a console C# applicaion is interesting.

My intended usage includes things like;

  • The user does something on the ASP.Net page that causes my server-side code to need to connect to another system and carry out lengthy operations, so I want to return control to the user quickly by firing that action to another thread. The user can keep watching progress through AJAX or simply move away - the web is stateless after all :)

  • Use of Fire and Forget patterns (lots of sample code out there, I want to understand more about how they work)

Thanks

Get "CLR Via C#" by Jeff Richter. Its the best .Net book I have ever read and has extensive information on threading.

alt text

Do you know any good book about the workings of the CLR, the .NET Framework and CIL as opposed to any specific .NET language?

Regardless of any other books, you will definitely need ECMA-335 standard for a detailed specification of CLR and CIL. With sufficient experience, it may actually be sufficient on its own.

Also, "Expert .NET 2.0 IL Assembler" looks like it matches your requirements, though I haven't read it and can't comment on its quality. Amazon description looks promising, though:

Topics include managed executable file structure, metadata table structure, Microsoft IL instructions, structured exception handling, managed and unmanaged code interoperation, executable file generation, and metadata manipulation API exposed by the common language runtime.

Although it mentions C# on the cover CLR via C# is a very good read to discover the ins and outs of the CLR.

This is a little dated but this is the book I used to learn .NET back then. Still relevant today as most things expanded but not changed. Essential .NET, Volume I: The Common Language Runtime

I am looking for web sites or books that would help a C++ developer to pick up C#. So far, this is the best one I've found.

Frankly, when I learned .NET, it was difficult to understand it in many ways from a C++ background. I found that trying to fit C# into a C++ mindset actually worked against me - not for me.

I wouldn't focus on trying to find something that's C# for C++ developers - try to just find good resources for C# in general. Good, detail C# and .NET framework books will get you there, and your C++ background will just help you understand the details a bit better. Learning C# will be about learning the frameworks, the expected manner of doing things, and forgetting a lot of C++ habits.

I would recommend a couple of detailed books that aren't focused on beginner topics, such as CLR via C# and C# in Depth.

I also think that the Framework Design Guidelines was probably the most valuable resources for getting me to think in C#/.NET instead of C++ - it really goes into why the framework is the way it is, and learning how to write code that other C# developers will want to maintain. The guidelines are available online, but the book is very helpful in that it also explains the reasons behind the guidelines, not just the "rules."

I find Peter Sestoft's Java Precisely to be a nice concise reference to Java for C++ programmers; he also is the author of C# Precisely which is written in the same spirit, though I haven't read it so I can't speak to it.

In the following c# code, how do I get rid of the objects when it's no longer useful? Does it get taken care of automatically, or do I need to do something?

public void Test()
{
   object MyObject = new object();

   ... code ...
}

The short answer is: unless it has unmanaged resources (file handles etc) you don't need to worry.

The long answer is a bit more involved.

When .NET decides it wants to free up some memory, it runs the garbage collector. This looks for all the objects which are still in use, and marks them as such. Any local variable (in any stack frame of any thread) which may still be read counts as a root as do static variables. (In fact I believe that static variables are referenced via live Type objects, which are referenced via live AppDomain objects, but for the most part you can regard static variables as roots.)

The garbage collector looks at each object referred to by a root, and then finds more "live" references based on the instance variables within those objects. It recurses down, finding and marking more and more objects as "live". Once it's finished this process, it can then look at all the rest of the objects and free them.

That's a very broad conceptual picture - but it gets a lot more detailed when you think of the generational model of garbage collection, finalizers, concurrent collection etc. I strongly recommend that you read Jeff Richter's CLR via C# which goes into this in a lot of detail. He also has a two part article (back from 2000, but still very relevant) if you don't want to buy the book.

Of course all this doesn't mean you don't need to worry about memory usage and object lifetimes in .NET. In particular:

  • Creating objects pointlessly will cost performance. In particular, the garbage collector is fast but not free. Look for simple ways to reduce your memory usage as you code, but micro-optimising before you know you have a problem is also bad.
  • It's possible to "leak" memory by making objects reachable for longer than you intended. Two reasonably common causes of this are static variables and event subscriptions. (An event subscription makes the event handler reachable from the event publisher, but not the other way round.)
  • If you use more memory (in a live, reachable way) than you have available, your app will crash. There's not a lot .NET can do to prevent that!
  • Objects which use non-memory resources typically implement IDisposable. You should call Dispose on them to release those resources when you're finished with the object. Note that this doesn't free the object itself - only the garbage collector can do that. The using statement in C# is the most convenient way of calling Dispose reliably, even in the face of an exception.

I want to know the in-memory representation of .NET constructs such as "interface", "class", "struct", etc. There's an excellent book for C++ object model - <Inside the C++ Object Model> by Stanley. Lippman, I want a similar book for .NET and C#.

I have read some books about .NET, but they are mostly about the logical usage of .NET. None of them talks about the physical in-memory layout info. I think it's necessary to know at least one implementation of .NET.

I have read about the "Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects" Could someone provide some hints about more in-depth books and articles?

If this info is not publicly avaialble. Shared source one like Mono or Shared Source CLI could be an option.

Many thanks.

The reason this information is not easily available is almost certainly deliberate on Microsofts behalf.

Microsoft created the .NET Framework and the CLR so you do not have to (unduly) worry yourself about where/how your objects are stored in memory (implmentation details). This "ignorance" is actually one of the biggest benefits of using .NET; you do not need to worry about issues such as manual memory allocation, processor/memory models etc.

The other benefit of this is that it improves security, ie it makes writing malicious code that much harder, although not impossible of course.

CLR Via C# by Jeff Richter is probably the best current book for "under the hood" type .NET information. Chapters 4, 5, 20 and 21 would probably be of most interest regarding layout of .NET types, although, as explained above, you will not find the same level of detail as the C++ object model.

I have a vb.net solution and I want to add there a new dll files written in c# and use the functionality from the dll, in the code written in vb.net.

I made several uses of it and it seems working all right, but is it a smart thing to do messing vb.net code with c# like I want to do .

And what a dangers of what I am doing ?

Thank a lot for help .

Your DLL is not a C# DLL, it's a .NET DLL. Once compiled, all you have is IL - doesn't matter what language it came from. Should be no problem, unless you encounter one of the odd edge cases where the DLL's interface includes something that is not supported by Visual Basic. But this would be very much an edge case.

The Common Language Specification, or CLS, defines the subset of .NET features that must be supported by a .NET language, and if your DLL is CLS compliant, then you can use it with no problems. If you are confused about the difference between the CLS, CTS, CLR etc, then I found the coverage of it in this book very helpful, though it is primarily a C# book.

I'm trying to bring myself up to speed on C#, having never developed for it before. In a previous question I asked about good book review sites, and through that I found a very positive (beginner-oriented) review for "Essential C#" but it was for a previous edition.

While I'm sure that it will still be a good book even if the quality dropped between versions, it raises an interesting question for me:

When beginning a new language, is it best to start with the latest version (e.g. C# 3.0/.Net 3.5) or should I go back a version or two and try to learn what got added to the language afterward?

The former seems better from the point of view of being up to date immediately, but the latter seems more pragmatic in that it's probably more likely a shop will be using a slightly older version of the language.

Learn the latest - but try to make sure you're rock solid on the language features from C# 1 and 2 rather than just learning the cool stuff from C# 3. Apart from anything else, you're still going to see straight C# 1 in many maintenance jobs.

It's worth being aware of how different features are implemented - in C# 2, nullable types and generics required CLR changes, but the rest (iterator blocks, anonymous methods, partial types etc) were just compiler magic. In C# 3 it's all compiler magic (with framework support for LINQ etc). You should really understand the fundamentals in CLR terms (what's a struct? what's a class?) and CLR via C# is a great way of learning this. Concentrate on the core technologies (the System.* types, IO, collections etc) before worrying too much about ASP.NET, WinForms, WPF etc. I'd include LINQ to Objects as a "core" API but not LINQ to SQL, for example.

I have Essential C# on my reading list at some point (for review purposes) - I've had a quick flick through what it offers, and it seems solid and thorough.

I've always worked with the standard Linux web stack (linux, apache, php, python, mysql) but have been given a great job opportunity working with a group that works with the Microsoft Web Stack (IIS, ASP.NET, MSSQL, C#).

There seems to be a pretty good Microsoft following here on SO. Where should I begin? Specific books, tutorials, online resources are appreciated.

If books are your best learning source then some I found helpful:

The third book is about the common language runtime (what executes compiled C# code).

I would suggest you read C# in Depth by Jon Skeet, who is a user here at SO. It will definitely help you master C#. The rest is gravy.

Sorry if I'm missing something obvious, but I'm trying to clear the controls (a series of user controls) from a FlowLayoutPanel - (panelName).Controls.Clear();. Unfortunately this doesn't seem to be calling the destructors for the objects on the panel - the User Objects column in the task manager just keeps going up and up, until it hits 10,000 and throws an excecption.

Does anyone know what I'm missing here?

.NET does not have the concept of destructors. .NET has something called "finalizers" which look syntactically like destructors in C#. For more information, check out Jeff Richter's awesome book on how the CLR works -- CLR via C#.

You may want the objects to implement the IDisposable pattern, and then call their Dispose() method when you're done with them.

I'm a long time Mac user, with a fair bit of programming experience and I wanted to try programming for windows. The thing is I don't know where to start, what should I learn first ? .Net, Win32 ?

[Clarification]: My ultimate goal would be to create a more or less complex application using the latest APIs however I like to know the underpinning of what I'm dealling with.

For rapid application development on windows, .NET seems to be the most efficient solution nowadays. But If you crave that extra ounce of performance out of your applications, I'd recommend giving Programming Windows and Windows via C/C++ a thorough read. Although some of the material is dated, a lot of it is still relevant with windows programming today. If you choose the .NET route some books to take a look at include Illustrated C# 2008, Accelerated C# 2008, and of course our own Jon Skeet's C# in Depth.

I'd recommend starting to program in .NET (C# or any other .NET language) since that's the most modern general application platform for Microsoft. I personally like the Richter books, CLR via C# and Applied Microsoft .NET Programming. Great starting points even though the 2nd book is a bit old and doesn't contain newer .NET features.

To truly learn the Windows platform, I totally agree with Bobby's suggestion to read Petzold's Programming Windows.

I recently applied for a C# junior programmer position and went through the initial phone screening, which I felt pretty good about. My current position is at a company that uses exclusively VB.NET development for .NET applications. I have worked with C# in college and some on my own after college and that is what I want to use for my career in the future.

I have the first O'Reilly Programming C# book for VS.NET 1.0 by Jesse Liberty from a college course. I remember this book being really helpful to me in college and I don't want to spend another $40+ dollars on a book.

So my question is how out-of-date is the first section of that book: "The C# language" (chapters 1 through 12) and even some of the later sections of the book? Has the language changed so much that it would be better to not read this book and use some other online sources? I have some new ASP.NET 3.5 books that should take care of the stuff that has changed for web applications, but I mainly want to get refreshed on the C# language.

Just to Clarify: This is a great website I just refreshed a few minutes later and had several great responses from other professionals!
Unfortunately I've been doing primarily support at my current position rather than new development so I'm not extremely familiar with all the new .NET classes. Majority of time is spent debugging/enhancing legacy apps (C++, VB6, with VB.NET applications) This is why I'm applying for a junior level posision and would be willing to take a slight paycut just to be able to do new development with guidance from a good lead developer. I think that would be a lot better for my future career goals.

O'Reilly Programming C# book for VS.NET 1.0 by Jesse Liberty is certainly out-of date. Much has changed from back than. I read that book and there are many sample code in it. But many things are done differently today:

  • lambda expressions instead of creating IComparer classes
  • Generics changed the way we write programs in C# a lot (don't use ArrayList any more)
  • LINQ
  • iterators instead of manually implementing IEnumerator
  • VS is now 3 generations more mature
  • ASMX web services are history, we use WCF today ...

I suggest Pro C# 2008 and the .NET 3.5 Platform, Fourth Edition or Jon Skeeet's C# in Depth.

CLR via C# by Jeff Richter is the book you're looking for. Worth its weight in gold.

Version 1.0 of that book will not cover things like generics, anonymous methods, etc.

Update: I probably confused memory usage issues with the UI sharing same thread as the processing (as pointed out by MusiGenesis below). However regarding the Memory usage. I am still not able to find VB.net specific syntax, although people have pointed out some great .Net and C# information below (and if I were more versed in those technologies, one could adapt to make work with VB.net).

I am creating a VB.Net application.

  • The application basically Parses Data Files located on the client machine into DataSet/DataTables.
  • Then using DataView, it breaks down the DataTables into manageble chunks, writes to XML and sends the XML data to a webservice.

The general concepts are working fine, however I am having issues where the Mem Usage on Task Manager keeps growing as the program is used to load more and more files.

On Startup, before doing anything, the VB application has 27,000 K. Once the file is parsed and even after I dispose of the File handle as well as the the data increases a lot. I strip out everything in the code and it still seems that memory in Mem Usage remains captured. There is no rhyme or reason as to why the Mem Usage is growing (i.e. sometimes it can grow by 20 mb when reading a 7mb file, however other times it does not increase at all, when reading a 3mb file). Sometimes, it appers to release some memory when the parsing is complete and other times it just holds.

I have looked at .Net Memory Profiler and have not really been able to make heads or tails from that.
I have read a lot on internet regarding Memory Management on .Net in General about Dispose and "Nothing" and DataSets, etc, however have not really found anything regarding VB.Net specifically.

My General Question is: Are there any good tutorials/books/blogs/etc that show a more in depth tutorial on managing memory in a VB.Net application (i.e. how/when to dispose/close, etc), or does anyone have some specific tips from there experience.

The best book to get on the subject that I've read is Jeff Richter's book, CLR via C#:

http://www.amazon.com/CLR-via-Second-Pro-Developer/dp/0735621632/ref=sr_1_1?ie=UTF8&qid=1252853101&sr=8-1-spell

If you want a VB.NET version, they have that for the first edition of the book, but I don't think there was enough interest to translate the book into VB.NET for the second version. If you want to really learn .NET, you should get comfortable with C#. In both languages, memory is managed by the CLR.

Can anyone suggest any good resources for getting started with IL. Specifically if anyone knows of any GOOD books or screencasts I would appreciate the feedback.

CLR via C# has a pretty basic intro into IL and a very in depth explanation as to what goes on in IL behind the scenes.

I have a structure something like this

struct MyStructure
    :IFoo
{
}

and a method like this:

public BarThisFoo(IFoo a)
{

}

my question is does passing the structure into that method "box" the structure, thus causing a garbage allocation?

Addendum: Before anyone says it, garbage collection is not free in this application, it's actually very sensitive to garbage collections, so allocation free code is important.

To avoid boxing you can use generics with constraints:

struct MyStructure
    :IFoo
{
}

public void BarThisFoo<T>(T a) where T : IFoo
{

}

See J. Richter CLR via C#, 2nd edition, chapter 14: Interfaces, section about Generics and Interface Constraints.

EDIT:

Example code

using System;
using System.Collections;

interface IFoo {
    void Foo();
}
struct MyStructure : IFoo {
    public void Foo() {
    }
}
public static class Program {
    static void BarThisFoo<T>(T t) where T : IFoo {
        t.Foo();
    }
    static void Main(string[] args) {
        MyStructure s = new MyStructure();
        BarThisFoo(s);
    }
}

IL code for method Main doesn't contain any box instructions:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       15 (0xf)
  .maxstack  1
  .locals init ([0] valuetype MyStructure s)
  IL_0000:  ldloca.s   s
  IL_0002:  initobj    MyStructure
  IL_0008:  ldloc.0
  IL_0009:  call       void Program::BarThisFoo<valuetype MyStructure>(!!0)
  IL_000e:  ret
} // end of method Program::Main

I'm looking for books and literature on the inner workings of the CLR (and/or possibly the DLR), my long time goal is to implement a simple language on the CLR.

A few starters for the CLR:

The DLR itself is Open Source, and its documentation is pretty handy.

Is there any detailed guide on how to use a resource embedded dll within a c# source? All the guides I find on Google don't seem to help much. It's all "make a new class" or "ILMerge" this and ".NETZ" that. But I'm not sure on how to use the ILMerge and .NETZ stuff, and the guides on classes leave out what to do after making the class file, since I find nothing new after doing so. For example, this. After adding the class and function, I have no idea on how to reach out to get the dll from my resources.

So, to be specific, what I'm looking for is a guide on how to use a .dll file that was embedded into Resources to be able to call a class, without and parts left out. Please keep in mind that I am not very experienced with C# coding. Thanks in advance. :D

PS. Try not to use those big words. I tend to get lost easily.

You can get a Stream to the DLL using Assembly.GetManifestResourceStream, but in order to do anything with it you'll either need to load it into memory and call Assembly.Load, or extract it to the file system (and then quite possibly still call Assembly.Load or Assembly.LoadFile, unless you've actually already got a dependency on it).

After loading the assembly you'd have to use reflection to create instances of classes or call methods etc. All of this is quite fiddly - and in particular I can never remember the situations in which to call the various overloads of Assembly.Load (or similar methods). Jeff Richter's "CLR via C#" book would be a useful resource to have at your desk.

Could you give more information about why you need to do this? I've used manifest resources for various things, but never to include code... is there any reason you can't ship it alongside your executable?

Here's a complete example, albeit without error checking:

// DemoLib.cs - we'll build this into a DLL and embed it
using System;

namespace DemoLib
{   
    public class Demo
    {
        private readonly string name;

        public Demo(string name)
        {
            this.name = name;
        }

        public void SayHello()
        {
            Console.WriteLine("Hello, my name is {0}", name);
        }
    }
}

// DemoExe.cs - we'll build this as the executable
using System;
using System.Reflection;
using System.IO;

public class DemoExe
{
    static void Main()
    {
        byte[] data;
        using (Stream stream = typeof(DemoExe).Assembly
               .GetManifestResourceStream("DemoLib.dll"))
        {
            data = ReadFully(stream);
        }

        // Load the assembly
        Assembly asm = Assembly.Load(data);

        // Find the type within the assembly
        Type type = asm.GetType("DemoLib.Demo");

        // Find and invoke the relevant constructor
        ConstructorInfo ctor = type.GetConstructor(new Type[]{typeof(string)});
        object instance = ctor.Invoke(new object[] { "Jon" });

        // Find and invoke the relevant method
        MethodInfo method = type.GetMethod("SayHello");
        method.Invoke(instance, null);
    }

    static byte[] ReadFully(Stream stream)
    {
        byte[] buffer = new byte[8192];
        using (MemoryStream ms = new MemoryStream())
        {
            int bytesRead;
            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, bytesRead);
            }
            return ms.ToArray();
        }
    }
}

Building the code:

> csc /target:library DemoLib.cs
> csc DemoExe.cs /resource:DemoLib.dll

What are good c++ to C# articles/tutorial or books? I am reading http://msdn.microsoft.com/en-us/magazine/cc301520.aspx and will read http://andymcm.com/csharpfaq.htm and http://www.ondotnet.com/pub/a/dotnet/2002/02/11/csharp_traps.html afterwards. Have any of you read any good books for ppl who have a strong understanding of programming && || C++ on the C# language (and libraries)?

If you're coming from C++, I think the best book to start with is CLR via C#. It will give you both a solid introduction to C# while also acclimating you to life in the CLR. The latter may be more of a stumbling block for someone with a solid C++ background.

I am currently reading Jon Skeet's C# in Depth. It is the best treatment I have seen for C# 2 and 3. If you are an advanced C++ programmer and you have some familiarity with C#, this is the book to take your C# competence to mastery.

Jon provides insights into the evolution of C# and insights into the various new language features. Not just the "hows" but also the "whys". Again, approach it after reading a beginning C# book. It doesn't cover the basic stuff which is covered many times by numerous other C# books.

I recommend Accelerated C# book for programmers who's came from C++ and Java Languages.

What are the ways to reduce the amount of memory my applications take in RAM?..Because even 30kb application loads ~20Mb of "unneeded" dlls.Am i mistaking when i think that any .NET app takes at least 10Mb in working set of memory when we need a form with text in it? Couldn't find any explanation of this :(

PS question is closed. But i suggest everyone interested in how CLR works read this: CLR via C#

I found this post helpful.

All my past programming experience has been in C++ on VS2003/8, Mostly service based and completely self taught.

2 Years ago I had to create my first real GUI app and (Foolishly) choose MFC. I got the app working but it took a long time & was a bit of a nightmare to learn MCF (and its many shortcomings) but I ended up with a reliable workable app which was difficult to change or extend.

Again I have to create another GUI app more complex than the first and again this will be created from scratch and will only ever be used on windows.

I had put off learning C# for a long time but not wishing to re-visit MFC have decided that the new application with be birthed in VS2010 and WPF 4 will be the midwife.

Trying to avoid the several expensive (Time wise) mistakes I made previously. Im looking for for good books/tutorials on the current versions of C# 4 & WPF 4 and also general advice on the best approach.

The application will do several things one of them would persisting info in a SQL DB. So Im thinking LINQ for that?

Please chip in...

For WPF I'm a huge fan of Apress' Pro WPF

I agree with the others regarding 3.5 vs 4.0 - not much difference when you are starting out. It's mostly cornercases and new controls (which were also in the WPF toolkit for 3.5sp1).

i've been using .Net from when it was a Beta and it has been a wonderful thing seeing it evolve to what it currently is. I can assure you that you are making the right decision!

You will be using LINQ not just for SQL, but anywhere in your code (where performance is not critical).

So, here are some resources i found best over the years..

C#

  • Programming C# by O'reilly - great for beginner to mid level programmers. quick read covers all the basics.
  • For the most In-Depth disection of .Net framework 4.0 CLR Via C# - Jeffrey Richter This book is not only interesting, but gives amazing insight into why 4.0 has the features it has and how it works under the covers.

LINQ

  • besides a ton of online resources, there is LinqPad. Amazing app that lets you see/modify just about every style of linq programming there is
  • There is also Entitiy Framework, which replaced LinqToSql, but I wouldn't recommend starting with that. Lots of gotchas (at least in 3.5 when i used it)

WPF

if you prefer watching demos, channel9.msdn.com , and MSDN webcasts are a great resource. Ton of stuff there. (be sure to search past events)

I know there's a lot of resource for this via google, but I just wanted to hear personally from people who have experienced this before. I've programmed in C for 3 years and C++ for a year and now I am moving to C#. I know this is not going to be a so hard transition but could you guys that had this same experience with me share resources on a good book, article, or blog to make my study experience more efficient. Any tips/tricks or gotchas when moving to C#?

Here's one article that I can find via google. Looking for more goodies from experienced developers here.

Richter's CLR Via C# book is the one that helped me to migrate.

I've been playing around with c++ lately and wondered why there were so many global functions. Then I started thinking about programming in c# and how member functions are stored, so I guess my question is if I have a:

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

and then I do something silly like adding 1,000,000 Foo's to a list; does this mean I have 1,000,000 Foo objects sitting in memory each with there own Bar() function? Or does something much more clever happen?

Thanks.

Nope, there is only one instance. All instances of a class point to an object that contains all the instance methods that take an implicit first parameter affectionately called this. When you invoke an instance method on an instance the this pointer for that instance is passed as the first parameter to that method. That is how the method knows all the instance fields and properties for that instance.

For details see CLR via C#.

This is, of course, complicated by virtual methods. CLR via C# will spell out the distinction for you and is highly recommended if you are interested in this subject. Either way, there is still only one instance of each instance method. The issue is just how these methods are resolved.

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.

Most C# developers developers, like me have a good solid grasp on the .net framework and the C# language. But I've yet to come across a book that can take a very good c# developer to the next level of C# mastery.

I am looking for a book that can help me make that transition. Dealing with issues like theory on having more robust C# code when connecting to external systems etc. Error logging techniques, and generally better memory usage, and re factoring.

Anyone know of a good book, that's worth the read?

The best book I have found for C# internals is CLR via C# by Jeffrey Richter.

Effective C# and More Effective C# by Bill Wagner come highly recommended

Not a C# book per se, but Design Patterns (Gamma et al) might be a good introduction to more abstract, architectural concepts.

Right now, I'm more into design & maintenance of MFC based application. I'm seeing good progress and requirement for C#.Net application.

With this background knowledge, how easy or difficult is to learn C#.Net? Is there any tutorials available online that helps MFC developers to easily learn C#.Net quickly?

Any help on this much appreciated!

You know MFC, so you know how to program a framework.

In my opinion, .Net framework is easier to program than MFC, you need to know two things:

  1. C# and CLR. You need to study a new language C# and the standard libraries in .Net, like strings, etc. A good reference is CLR via C#.

  2. Windows Forms. Windows Forms is far easier than MFC and more clean. You can find a lot of tutorials online.

Suppose i have the code snippet as follows : ( clarification purpose/not well formed)

class Employee
{
    #region fields

    protected string _empID;

    protected string _empName;

    protected readonly string _ssn;

    #endregion

    public Employee(){}   

    public Employee(string _empID,string _empName,string _ssn)
    {
        this._empID =_empID;
        this._empName=_empName;
        this._ssn = _ssn;
    }
}


class Manager : Employee
{
    private string _branchID;

    public Manager(int  _branchID):base(string _empID,string _empName,string _ssn)
    {
        this._branchID=_branchID;
    }
}

static void Main()
{
   Manager mgr = new Manager("1","sam","xxx","Branch1");
}

Using base keyword I am invoking parent class constructor .

In this case how the inheritance is organized? I have some bad assumptions as follow:

As Manager is derived from Employee, Manager class is filled with (empID,empName,ssn)

-----------------
 Manager
-----------------
empID
empName
ssn
branchID

step 1 : constructor invoking :base( "1","sam","xxx")

step 2 : base class(Employee) constructor fills the derived class filed (empID,empName,ssn)

step 3 : branchID is assigned by derived class constructor

.......

My question is

  • If a class is derived from base class, the derived class also has the base class' hidden fields?
  • Derived class shares Base class fields? I mean separate memory block is allocated for Base class and derived class?
  • An object starts with a header which includes a pointer to its actual type information. That type information includes the vtable to work out which method actually means what. The CLR uses that vtable at execution time to call overridden methods.

    After the object header comes all the instance data associated with the object - including base class fields and derived class fields. It's all in one place - it's not like the instance of the derived class also has a reference to a "hidden" instance of the base class. I strongly suspect that the base class fields come first, as then methods in the base class can still refer (in assembly) to the same fields via offsets from the "top" of the object... but I don't have anything in front of me to confirm this.

    IIRC, Jeff Richter's "CLR via C#" talks about all of this in some depth - it's a great source of information for this kind of thing.

    Yes, the derived class will also contain the base class fields in memory. On page 112 of CLR via C#, Jeffrey Richter says:

    "Then, M3 executes its code to construct a Manager object. This causes an instance of the Manager type, a Manager object, to be created in the managed heap, as shown in Figure 4-9. As you can see, the Manager object-as do all objects-has a type object pointer and sync block index. This object also contains the bytes necessary to hold all of the instance data fields defined by the Manager type as any instance fields defined by any base classes of the Manager type (in this case, Employee and Object)." (Emphasis Added)

    It's also worth noting that a separate block of memory is created for any base types. But ONLY for the type data (so only once, at most). When you create a Manager object (which derives from Employee), the CLR will ensure that there is a Manager Type Object, and an Employee Type Object on the heap.

    1) Richter, Jeffrey. CLR via C#. Redmond: Microsoft Press, 2006. (Amazon Link)

    To date I've done a lot of low-level programming (kernel-mode device drivers, native code, etc.) on both Windows and UNIX with C++, C and Ada95. I'm considering to make a career jump to application-specific programming where I can learn a business alongside software development and not just be a low-level hardware interface guy.

    Besides learning SQL and basic databases, for various reasons, I've decided to go with the .NET stack rather than the Java stack. I'm not really interested in UIs, but more so server and back-end development for the time being, so I'm trying to avoid tech like WPF and CSS/Javascript/AJAX for now.

    What .NET technologies should I be trying to learn to make myself more "modern" and competitive in the job market? Do I need to try to master linq, ADO.NET, ASP.NET, and WCF as well?

    Considering your background I think you'd be interested in a book titled CLR via C#. It may be a bit too academic to be of any direct use for a while, but it's really helped me understand how it all works together.

    I have a structure in C#.net. I have created an object of that structure. I need to cast this object of structure into ArrayList. I am using :

    OrderMessageStructure.OrderMessage orderToModify = new OrderMessageStructure.OrderMessage();
    
    object neworderobject = (object)orderToModify;
    ArrayList arr = new ArrayList();
    arr = (ArrayList)neworderobject;
    

    But I am getting error "Unable to cast object of type 'OrderMessage' to type 'System.Collections.ArrayList'."

    How to convert object/structure into ArrayList?

    You can't just cast any object into another object in C#. Its a type safe language.

    You need to create an ArrayList and Add() your struct to it.

    Better yet, create a List<StructType>() and add your struct to that.

    CLR Via C#. Read it.


    OrderMessageStructure.OrderMessage orderToModify = 
      new OrderMessageStructure.OrderMessage();
    
    ArrayList arr = new ArrayList();
    arr.Add(orderToModify);
    

    I just cant seem to understand these pillars of .NET.

    As already mentioned, CLS is subset of CTS. But there is much more in the actual definition of these terms.

    I suggest reading CLR via C#.

    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:

    This might be a pretty straightforward question, but I'm trying to understand some of the internal workings of the compilation.

    Very simply put, imagine an arbitrary object being instantiated. This object is then allocated on the heap. The object has a property of type PointF (which is value type), with a get and a set method.

    Imagine the get and the set method containing a few calculations for doing their work. How and where (stack/heap) and when is this code instantiated?


    This is the background for this question:

    I'm writing get and set methods for an object and these methods need to be accessed very frequently. The get and set code in itself is rather massive so I feared that in a worst case scenario the methods would be instantiated as an object or a value type with all internal code for every access of the property. On the other hand the code is probably instantiated when the main object is created and the CPU is simply told to jmp to the property code start. Anyway, this is what I want to have clarified.

    I don't have my copy of CLR via C# here with me, but getters and setters of properties are just methods on the class with special decoration. Jeffery Richter's excellent book will have all the nitty-gritty details.

    i am programmer but not good i am working with c# , asp.net and MVC too. so how i can improve our coding skill for develop a better web apps. means how can i learn it.

    Obviously you need some good ASP.NET MVC resources as the other answers have pointed out. It is also worth investing time in learning about the .NET framework itself. For this purpose I thoroughly recommend CLR via C# by Jeffrey Richter.

    What I think you should start with is some beginning book and move towards professional. One book could be

    http://www.amazon.com/Beginning-ASP-NET-3-5-2008-Professional/dp/1590598911

    once u understand this book then u can for MVC book like.

    www.amazon.com/Pro-ASP-NET-Framework-Steven-Sanderson/dp/1430210079

    In between try to learn by googling topics like. TDD(Test Driven Development), DI(Dependency Injection) and Other design Patterns

    I'm doing a compiler design class on the topic of memory management. I am reading about garbage collection and noticed that most of that low level stuff takes place with C/C++ code. I have a few questions about the c# compiler.

    1. Was .net framework part for memory management written in c/c++?
    2. How does .net manages memory?
    3. Does their internal garbage collection uses malloc()?
    4. What method of garbage collection does the .net framework use?

    I'd probably use answers to generate new questions but I'm not sure If I should create a new question or edit this one.

    Much of this type of information can be found in CLR via C# (or from Amazon). Note that it sounds like the book will be updated for .NET 4.0.

    I'm learning C++, but i see that .Net is a very nice framework, then i want to ask: "It's difficult to develop in .Net?", remember that i have some knowledge of VB and Delphi. I'm using Windows Vista Ultimate. Thanks!

    C++ to .Net should be better framed as "C++ to C# or VB.Net".

    Remember, .Net is a framework, NOT a language. C# , VB.Net, or other .Net language are built on .Net framework. I find it easier to learn C# if you have some other object oriented language background such as C++ or Java. It's just anther language with the similar syntax. However, .Net framework is a much, much bigger area , and it takes a lot of real world experiences to master it or portion of it. For example, .Net framework has a lot of web framework which you can only probably learn it by doing asp.net, a lot of regular expression library which you can learn by doing a lot of string processing.

    For C# language, which is the most popular language on .Net platform, I recommend the book C# in Depth. For .Net framework itself, i recommend CLR via C#.

    My background: 1. I recently graduated college (BS in CS), and have been working full time as a MOSS 2007 software developer for 7 months. Any server side code I write is in C# using asp.net 2.0. 2. I have mostly (Java, C) experience and a strong grasp of OOP from college.

    What I'm looking for: A book on asp.net 2.0 that will help me understand the framework. If code examples are in C# or there is additional information on C# development, that is a plus, but my primary goal is to understand how the framework works. For example, I know that Page_Init gets called, then Page_Load, etc but how does that work internally? Any recommendations?

    Right now I'm looking at the following books: Professional ASP.NET 2.0 Programmer to Programmer, Professional ASP.NET 2.0 Special Edition, CLR via C#

    Given the info above, can anyone help me limit my choices? I like the reviews for CLR via C# the best, but I'm not convinced that it will provide enough info about asp.net itself. For the other two titles, I'm wary that they assume too much knowledge of asp.net v1, but I have no such experience. Thanks.

    CLR via C# is not a book about ASP.NET but it's a must for any developer working in .NET to understand it's inner workings. I say again, a must.

    Either of mentioned ASP.NET books are good and provides what you need.