background preloader

C#

Facebook Twitter

.net

Designpattern. Dynamic Language Runtime Talk at PDC. Recursive lambda expressions. This is a very geeky post. The tiny piece of useful information comes right at the bottom. The rest of it is all artifacts of the obscure art of doing lambda calculus in C#, which can also be characterized as doing very much with very little, sacrificing only readability. People sometimes complain that you cannot write a lambda expression that is recursive. Good old factorial, for instance, how to write that as a lambda expression?

Well the fathers of lambda calculus, who invented the lambda expressions in the 1930’s struggled with that, too, and as you might have guessed they came up with a solution. In this post let us stand on the shoulders of those giants and see how you can get recursion into your own lambda expressions in C#. How to write factorial So what you really want is to be able to write the lambda expression: x => x == 0 ? But that won’t work – we’re using fac to define fac, but we haven’t defined it yet! Fac => x => x == 0 ? Fixed points Func<Func<int,int>,Func<int,int>> F = What&#039;s the difference, part one: Generics are not templates.

Because I'm a geek, I enjoy learning about the sometimes-subtle differences between easily-confused things. For example: I'm still not super-clear in my head on the differences between a hub, router and switch and how it relates to the gnomes that live inside of each.Hunks of minerals found in nature are rocks; as soon as you put them in a garden or build a bridge out of them, suddenly they become stones.When a pig hits 120 pounds, it's a hog. I thought I might do an occasional series on easily confounded concepts in programming language design.

Here’s a question I get fairly often: public class C{ public static void DoIt<T>(T t) { ReallyDoIt(t); } private static void ReallyDoIt(string s) { System.Console.WriteLine("string"); } private static void ReallyDoIt<T>(T t) { System.Console.WriteLine("everything else"); }} What happens when you call C.DoIt<string>?

Because that’s not the choice that is presented. ReallyDoIt("hello world"); then we would pick the “natural” version. C# is now a better language than Java. I’m currently teaching myself C# (with .NET to follow); my client is building a new data warehouse, and the support tools will be Windows-based. As a newly minted consultant, it also can’t hurt to have .NET/C# experience under my belt, even if I generally prefer to do my development anywhere but Windows. As a consultant, I need to maximize the possibility of getting future contracts; if that means doing Windows, I’ll do Windows (and program where I’d prefer to program at home). As pretty much anyone who knows me knows, I am not a huge fan of Microsoft. I’ve spent a large part of my career programming on Unix-like systems.

From 1999 to 2008, I worked for an independent software vendor, as a core member of their development team; the product was written almost entirely in Java. I like the Java VM. But Java, the language, depresses me lately. Worse, though, for Java enthusiasts: Java has fallen behind C#. Lambdas, which are way better than anonymous inner classes. C# string.Empty vs “” As we know we have two ways to set a variable value to an empty string. We can just set it to empty quotes “” or set it to string.Empty, but what is the difference and is there one at all ? If we will look at the .NET String.cs we will see the next line: public static readonly String Empty = ""; public static readonly String Empty = ""; The above line can tell us that string.Empty is not a constant as we would like to believe but a readonly field.

The question is why, why static readonly and not a constant. The answer is in the same String.cs comments of the Empty field. // The Empty constant holds the empty string value. Now, let’s make some test. As we can see string.Empty and “” have the same behavior except the “switch” because string.Empty is not a constant. And of course the most important question – is there a performance differences between the two ? We can see from the results that the comparison with string.Empty is a little bit faster but it's negligible.

Rating: 4.2/5 (9 votes cast) C#: Removing duplication in mapping code with partial classes. One of the problems that we’ve come across while writing the mapping code for our anti corruption layer is that there is quite a lot of duplication of mapping similar types due to the fact that each service has different auto generated classes representing the same data structure. We are making SOAP web service calls and generating classes to represent the requests and responses to those end points using SvcUtil. We then translate from those auto generated classes to our domain model using various mapper classes. One example of duplication which really stood out is the creation of a ‘ShortAddress’ which is a data structure consisting of a postcode, suburb and state.

In order to map address we have a lot of code similar to this: Where the XsdGeneratedAddress might be something like this: It’s really quite boring code to write and it’s pretty much exactly the same apart from the class name. Sadly we are in C# which doesn’t yet have that capability! Which uses this extension method: Asynchronous methods, C# iterators, and Tasks. More and more, developers are realizing the significant scalability advantages that asynchronous programming can provide, especially as it relates to I/O. Consider an application that needs to copy data from one stream to another stream, such as is being done in the following synchronous implementation: static void CopyStreamToStream(Stream input, Stream output) { // Buffer space for the data to be read and written byte [] buffer = new byte[0x2000]; // While there’s data to be read and written while(true) { // Read data.

If we weren’t able to read any, bail. // Otherwise, write it out and start over again. Int numRead = input.Read(buffer, 0, buffer.Length); if (numRead == 0) break; output.Write(buffer, 0, numRead); } } One solution to this problem is through compiler support. A compiler could recognize this synchronous pattern and translate it into an asynchronous one. That’s quite lovely. IEnumerable<ThingThatHasCallbackWhenCompletes> AsyncMethod() { ... Much simpler. Functional Optimistic Concurrency in C# A few months ago Phil Haack wrote about how C# 3.0 is a gateway drug to functional programming. (Yeah, that's how long ago I started writing this blog.)

I couldn't agree more. I find myself solving problems using functional rather than imperative programming quite often nowadays. It's much more elegant for many problem spaces. Before we go any further, here's the sample app used for this article. One problem space that fits very well with functional patterns is in developing apps that have to use optimistic concurrency to maintain data consistency at scale. Multiple rival lords are attacking my Kingdom at once trying to steal my most prized vassal, my wife!

In this common use case there are a number of subtleties. So what does all that mean? There are a a number of potential strategies for managing these change conflicts in the persistent store – a few beefy Microsoft SQL Server databases in our case. As you can see it's really straight forward. And, finally, we have the Retry method: C# Tutorial - Using The ThreadPool. A thread pool takes away all the need to manage your threads - all you have to do is essentially say "hey! Someone should go do this work! ", and a thread in the process' thread pool will pick up the task and go execute it. And that is all there is to it. Granted, you still have to keep threads from stepping on each other's toes, and you probably care about when these 'work items' are completed - but it is at least a really easy way to queue up a work item.

In fact, working with the ThreadPool is so easy, I'm going to throw all the code at you at once. We have three arrays at the top of the program: one for input to the work items (inputArray), one for the results (resultArray), and one for the ManualResetEvents (resetEvents). So we initialize these arrays, and then we get to a for loop, which is where we will be pushing out these work items. So what are we queuing here? So what are we doing in this DoWork function? Pretty simple, eh? That's it for this intro to thread pools in C#. Csharpfullscreenexample - Google Code.

C# From a Java Developer&#039;s Perspective. The C# language is an object-oriented language that is aimed at enabling programmers to quickly build a wide range of applications for the Microsoft .NET platform. The goal of C# and the .NET platform is to shorten development time by freeing the developer from worrying about several low level plumbing issues such as memory management, type safety issues, building low level libraries, array boundschecking , etc. thus allowing developers to actually spend their time and energy working on their application and business logic instead.

As a Java developer the previous sentence could be described as "a short description of the Java language and platform" if the words C# and the .NET platform were replaced with words Java and the Java platform. What follows is an overview of similarities and differences between the language features and libraries of the C# and Java programming languages based on my experience using both languages. Five-Dollar Words For Programmers, Part Three: Homoiconic. Hi Eric, I have two comments: 1) having a full AST in C# would be great.

And I don't say this because it just sounds cool, but because it would enable better solutions for a number of problems we can currently only solve in very clumsy ways. However, I want to bring your attention to the problem of meta-programming in the static .NET type system in general. Even if we get AST-level access to an entire class, and be able to modify that AST (which is currently not possible, and copying ASTs is not always the better solution), we're still in a much worse position than any Lisp programmer would be. "In ye olden times", the .NET type system was simple. It is not an accident that we found quite a few deep bugs in the .NET framework when we created a library that brings real mixins to C#. I'm with Fabian, finding a way to enable meta-programming in a static .NET language is not rocket science, humankind has been there before.

(How could that look? 2) This is a pet topic of mine. Is that it? Parser in C# C# C♯ is intended to be a simple, modern, general-purpose, object-oriented programming language.[6] Its development team is led by Anders Hejlsberg. The most recent version is C♯ 5.0, which was released on August 15, 2012. The ECMA standard lists these design goals for C#:[6] Due to technical limitations of display (standard fonts, browsers, etc.) and the fact that the sharp symbol (U+266F ♯ music sharp sign (HTML: &#9839;)) is not present on the standard keyboard, the number sign (U+0023 # number sign (HTML: &#35;)) was chosen to represent the sharp symbol in the written name of the programming language.[8] This convention is reflected in the ECMA-334 C# Language Specification.[6] However, when it is practical to do so (for example, in advertising or in box art[9]), Microsoft uses the intended musical symbol.

C# used to have a mascot called Andy (named after Anders Hejlsberg). In the course of its development, the C# language has gone through several versions: C# has the following syntax: The A-Z of Programming Languages: C# Computerworld is undertaking a series of investigations into the most widely-used programming languages. Previously we have spoken to Alfred v. Aho of AWK fame, S. Tucker Taft on the Ada 1995 and 2005 revisions, Microsoft about its server-side script engine ASP, Chet Ramey about his experiences maintaining Bash, Bjarne Stroustrup of C++ fame, and Charles H. Moore about the design and development of Forth. We’ve also had a chat with the irreverent Don Woods about the development and uses of INTERCAL, as well as Stephen C. In this interview Microsoft's leader of C# development, Anders Hejlsberg, took some time to tell Computerworld about the development of C#, his thoughts on future programming trends, and his experiences putting out fires.

(Please note that due to popular demand we are no longer following alphabetical order for this series. What were the fundamental flaws in other languages that you believe drove the development of Common Language Runtime (CLR), and in turn, C#? Emacs is better than Visual Studio as a C# Development Tool?!! I recently spent some time fiddling with my setup of emacs on Windows. I use emacs for lots of stuff; just now I optimized my setup for development of C# apps. I knew of the JDEE, which has been around for a long time. JDEE is the Java Development Environment for Emacs; it used to go by the moniker of JDE. It has code completion (aka "intellisense"), compiling tools (ant I think), syntax highlighting, an "immediate window" (BeanShell) for evaluating Java expressions right now, that kind of thing. So lacking an integrated set of add-ons, what would be the best Emacs setup, for C# development?

First, emacs v22.2. There were some places where I came up short. I also checked out a package called folding.el. I don't have integrated debugging, but I can separately start up the clrdbg.exe which is included in the .NET SDK. I didn't bother with setting up unit testing. The upshot is, I have a pretty good development environment for C# now, in Emacs. How does Emacs compare to Visual Studio?