Csharpfaq

Where to get the Csharpfaq?. 11

How to contribute to the Csharpfaq?. 11

What will happen if you mail your C# programming problems to the authors?. 11

Csharpfaq1: General Questions about C#. 11

What is C#?. 11

Who supports C#? Who develops it? Why is it free?. 12

Which version of C# should I use?. 12

What are C# 1, C# 2, or C# 3?. 12

How stable is C#?. 12

Is C# difficult to learn?. 12

How does C# compare with other languages like Java, Python, C, C++, REXX, Scheme or Tcl?. 12

Can I do [task] in C#?. 13

When shouldn’t I program in C#?. 13

What’s the difference between C# and c-sharp?. 13

Is it a C# program or a C# script?. 13

What is a JAPH? JACH? JACSH?. 13

How can I convince others to use C#?. 13

Csharpfaq2: Obtaining and Learning about C#. 13

What machines support C#? Where do I get it?. 13

How can I get a binary version of C#?. 14

I don’t have a C compiler. How can I build my own C# compiler?. 14

I copied the C# compiler binary from one machine to another, but it doesn’t work. 14

I grabbed the sources and tried to compile but gdbm/dynamic loading/malloc/linking/… failed. How do I make it work?. 14

What modules and extensions are available for C#?. 14

Is there an ISO or ANSI certified version of C#?. 14

Where can I get information on C#?. 14

What are the C# newsgroups on Usenet? Where do I post questions?. 14

Where should I post source code?. 15

C# Books. 15

Which magazines have C# content?. 15

What mailing lists are there for C#?. 15

Where are the archives for mono and mono-devel?. 15

Where can I buy a commercial version of C#?. 15

Where do I send bug reports?. 15

What is csharp.com, csharp-station.com, csharphelp.com, codeproject.com, etc?. 15

Csharpfaq3: Programming Tools. 15

How do I do (anything)?. 16

How can I use C# interactively?. 16

Is there a C# shell?. 16

How do I find which modules/libraries are installed on my system?. 16

How do I debug my C# programs?. 16

How do I profile my C# programs?. 16

How do I cross-reference my C# programs?. 16

Is there a pretty-printer (formatter) for C#?. 17

Is there a ctags for C#?. 17

Is there an IDE or Windows C# editor?. 17

Where can I get C# macros for vi?. 17

Where can I get csharp-mode for emacs?. 17

How can I use curses with C#?. 17

How can I use X or Tk with C#?. 17

How can I make my C# program run faster?. 17

How can I make my C# program take less memory?. 17

Is it safe to return a reference to a local or lexical data?. 17

How can I free an array or hash so my program shrinks?. 18

How can I make my CGI script more efficient?. 18

How can I hide the source for my C# program?. 18

How can I compile my C# program into byte code or C?. 18

How can I get #!/usr/bin/csharp to work on [MS-DOS, NT, … ] ?. 18

Can I write useful C# programs on the command line?. 18

Why don’t C# one-liners work on my DOS/Mac/VMS system?. 18

Where can I learn about CGI or Web programming in C#?. 18

Where can I learn about object-oriented C# programming?. 19

Where can I learn about linking C with C#?. 19

I’ve read XYZ but I can’t embed C# in my C program; what am I doing wrong?. 19

When I tried to run my script, I got this message. What does it mean?. 19

What’s MakeMaker? [x:What is MSBUILD or Nant?] 19

Csharpfaq4: Data Manipulation. 19

Data: Numbers. 19

Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?. 19

Why is int() broken?. 19

Why isn’t my octal data interpreted correctly?. 20

Does C# have a round() function? What about ciel() and floor()? Trig functions?. 20

How do I convert between numeric representations/bases/radixes?. 20

Why doesn’t & work the way I want it to?. 21

How do I multiply matrices?. 21

How do I perform an operation on a series of integers?. 21

How can I output Roman numerals?. 22

Why aren’t my random numbers random?. 22

How do I get a random number between X and Y?. 22

Data: Dates. 22

How do I find the day or week of the year?. 22

How do I find the current century or millennium?. 22

How can I compare two dates and find the difference?. 22

How can I take a string and turn it into epoch seconds?. 23

How can I find the Julian Day?. 23

How do I find yesterday’s date?. 23

Does C# have a Year 2000 problem? Is C# Y2K compliant?. 23

Data: Strings. 23

How do I validate input?. 23

How do I unescape a string?. 23

How do I remove consecutive pairs of characters?. 24

How do I expand function calls in a string?. 24

How do I find matching/nesting anything?. 24

How do I reverse a string?. 24

How do I expand tabs in a string?. 24

How do I reformat a paragraph?. 24

How can I access or change N characters of a string?. 24

How do I change the Nth occurrence of something?. 25

How can I count the number of occurrences of a substring within a string?. 25

How do I capitalize all the words on one line?. 25

How can I split a [character] delimited string except when inside [character]?. 25

How do I strip blank space from the beginning/end of a string?. 27

How do I pad a string with blanks or pad a number with zeroes?. 27

How do I extract selected columns from a string?. 27

How do I find the soundex value of a string?. 27

How can I expand variables in text strings?. 27

What's wrong with always quoting "$vars"?. 27

Why don't my <<HERE documents work?. 27

Data: Arrays. 28

What is the difference between a list and an array?. 28

What is the difference between $array[1] and @array[1]?. 28

How can I remove duplicate elements from a list or array?. 28

How can I tell whether a certain element is contained in a list or array?. 28

How do I compute the difference of two arrays? How do I compute the intersection of two arrays?. 29

How do I test whether two arrays or hashes are equal?. 29

How do I find the first array element for which a condition is true?. 30

How do I handle linked lists?. 31

How do I handle circular lists?. 31

How do I shuffle an array randomly?. 31

How do I process/modify each element of an array?. 32

How do I select a random element from an array?. 32

How do I permute N elements of a list?. 32

How do I sort an array by (anything)?. 32

How do I manipulate arrays of bits?. 32

Why does defined() return true on empty arrays and hashes?. 33

Data: Hashes (Associative Arrays) [x:Dictionaries] 33

How do I process an entire hash?. 33

What happens if I add or remove keys from a hash while iterating over it?. 33

How do I look up a hash element by value?. 33

How can I know how many entries are in a hash?. 33

How do I sort a hash (optionally by value instead of key)?. 33

How can I always keep my hash sorted?. 33

What's the difference between "delete" and "undef" with hashes?. 33

Why don't my tied hashes make the defined/exists distinction?. 33

How do I reset an each() operation part-way through?. 33

How can I get the unique keys from two hashes?. 33

How can I store a multidimensional array in a DBM file?. 33

How can I make my hash remember the order I put elements into it?. 33

Why does passing a subroutine an undefined element in a hash create it?. 33

How can I make the C# equivalent of a C structure/C++ class/hash or array of hashes or arrays?. 33

How can I use a reference as a hash key?. 33

Data: Misc. 33

How do I handle binary data correctly?. 33

How do I determine whether a scalar is a number/whole/integer/float?. 33

How do I keep persistent data across program calls?. 34

How do I print out or copy a recursive data structure?. 34

How do I define methods for every class/object?. 34

How do I verify a credit card checksum?. 34

How do I pack arrays of doubles or floats for XS code?. 34

Csharpfaq5: Files and Formats. 35

How do I flush/unbuffer an output filehandle? Why must I do this?. 35

How do I change, delete, or insert a line in a file, or append to the beginning of a file?. 35

How do I count the number of lines in a file?. 37

How can I use Perl's -i option from within a C# program?. 37

How can I copy a file?. 38

How do I make a temporary file name?. 38

How can I manipulate fixed-record-length files?. 38

How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles?. 38

How can I use a filehandle indirectly?. 39

How can I set up a footer format to be used with write()?. 39

How can I write() into a string?. 39

How can I output my numbers with commas added?. 39

How can I translate tildes (~) in a filename?. 39

How come when I open a file read-write it wipes it out?. 39

Why do I sometimes get an "Argument list too long" when I use <*>?. 39

Is there a leak/bug in glob()?. 39

How can I open a file with a leading ">" or trailing blanks?. 39

How can I reliably rename a file?. 39

How can I lock a file?. 39

Why can't I just open(FH, ">file.lock")?. 40

I still don't get locking. I just want to increment the number in the file. How can I do this?. 40

All I want to do is append a small amount of text to the end of a file. Do I still have to use locking?. 40

How do I randomly update a binary file?. 40

How do I get a file's timestamp in C#?. 40

How do I set a file's timestamp in C#?. 40

How do I print to more than one file at once?. 40

How can I read in an entire file all at once?. 40

How can I read in a file by paragraphs?. 40

How can I read a single character from a file? From the keyboard?. 40

How can I tell whether there's a character waiting on a filehandle?. 40

How do I do a tail -f in C#?. 40

How do I dup() a filehandle in C#?. 41

How do I close a file descriptor by number?. 41

Why can't I use "C:\temp\foo" in DOS paths? Why doesn't `C:\temp\foo.exe` work?. 41

Why doesn't glob("*.*") get all the files?. 41

Why does C# let me delete read-only files? Why does -i clobber protected files? Isn't this a bug in C#?. 41

How do I select a random line from a file?. 41

Why do I get weird spaces when I print an array of lines?. 42

Csharpfaq6: Regular Expressions. 42

How can I hope to use regular expressions without creating illegible and unmaintainable code?. 42

I'm having trouble matching over more than one line. What's wrong?. 42

How can I pull out lines between two patterns that are themselves on different lines?. 42

I put a regular expression into $/ but it didn't work. What's wrong?. 42

How do I substitute case insensitively on the LHS while preserving case on the RHS?. 43

How can I make \w match national character sets?. 43

How can I match a locale-smart version of /[a-zA-Z]/?. 43

How can I quote a variable to use in a regex?. 43

What is /o really for?. 43

How do I use a regular expression to strip C style comments from a file?. 43

Can I use regular expressions to match balanced text?. 43

What does it mean that regexes are greedy? How can I get around it?. 45

How do I process each word on each line?. 45

How can I print out a word-frequency or line-frequency summary?. 45

How can I do approximate matching?. 45

How do I efficiently match many regular expressions at once?. 45

Why don't word-boundary searches with \b work for me?. 45

Why does using $&, $`, or $' slow my program down?. 45

What good is \G in a regular expression?. 45

Are regexes DFAs or NFAs? Are they POSIX compliant?. 45

What's wrong with using grep in a void context?. 45

How can I match strings with multibyte characters?. 45

How do I match a regular expression that's in a variable?. 45

Csharpfaq7: General C# Language Issues. 45

Can I get a BNF/yacc/RE for the C# language?. 46

What are all these $@%&* punctuation signs, and how do I know when to use them?. 46

Do I always/never have to quote my strings or use semicolons and commas?. 46

How do I skip some return values?. 46

How do I temporarily block warnings?. 46

What's an extension?. 46

Why do C# operators have different precedence than C operators?. 46

How do I declare/create a structure?. 46

How do I create a module?. 46

How do I create a class?. 46

How can I tell if a variable is tainted?. 46

What's a closure?. 46

What is variable suicide and how can I prevent it?. 46

How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?. 46

How do I create a static variable?. 46

What's the difference between dynamic and lexical (static) scoping? Between local() and my()?. 46

How can I access a dynamic variable while a similarly named lexical is in scope?. 46

What's the difference between deep and shallow binding?. 46

Why doesn't "my($foo) = <FILE>;" work right?. 46

How do I redefine a builtin function, operator, or method?. 46

What's the difference between calling a function as &foo and foo()?. 46

How do I create a switch or case statement?. 46

How can I catch accesses to undefined variables, functions, or methods?. 47

Why can't a method included in this same file be found?. 47

How can I find out my current package?. 47

How can I comment out a large block of C# code?. 47

How do I clear a package?. 47

How can I use a variable as a variable name?. 47

What does "bad interpreter" mean?. 47

Csharpfaq8: System Interaction. 47

How do I find out which operating system I'm running under?. 48

How come exec() doesn't return?. 48

How do I do fancy stuff with the keyboard/screen/mouse?. 48

How do I print something out in color?. 48

How do I read just one key without waiting for a return key?. 48

How do I check whether input is ready on the keyboard?. 48

How do I clear the screen?. 48

How do I get the screen size?. 48

How do I ask the user for a password?. 48

How do I read and write the serial port?. 48

How do I decode encrypted password files?. 48

How do I start a process in the background?. 48

How do I trap control characters/signals?. 48

How do I modify the shadow password file on a Unix system?. 48

How do I set the time and date?. 48

How can I sleep() or alarm() for under a second?. 48

How can I measure time under a second?. 48

How can I do an atexit() or setjmp()/longjmp()? (Exception handling) 48

Why doesn't my sockets program work under System V (Solaris)? What does the error message "Protocol not supported" mean?. 48

How can I call my system's unique C functions from C#?. 48

Where do I get the include files to do ioctl() or syscall()?. 48

Why do setuid C# scripts complain about kernel problems?. 48

How can I open a pipe both to and from a command?. 48

Why can't I get the output of a command with system()?. 49

How can I capture STDERR from an external command?. 49

Why doesn't open() return an error when a pipe open fails?. 49

What's wrong with using backticks in a void context?. 49

How can I call backticks without shell processing?. 49

Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?. 49

How can I convert my shell script to C#?. 49

Can I use C#to run a telnet or ftp session?. 49

How can I write expect in C#?. 49

Is there a way to hide C#'s command line from programs such as "ps"?. 49

I {changed directory, modified my environment} in a C# script. How come the change disappeared when I exited the script? How do I get my changes to be visible?. 49

How do I close a process's filehandle without waiting for it to complete?. 49

How do I fork a daemon process?. 49

How do I find out if I'm running interactively or not?. 49

How do I timeout a slow event?. 49

How do I set CPU limits?. 49

How do I avoid zombies on a Unix system?. 49

How do I use an SQL database?. 49

How do I make a system() exit on control-C?. 49

How do I open a file without blocking?. 49

How do I tell the difference between errors from the shell and C#?. 49

How do I install a module from CPAN?. 49

What's the difference between require and use?. 50

How do I keep my own module/library directory?. 50

How do I add the directory my program lives in to the module/library search path?. 50

How do I add a directory to my include path (@INC) at runtime?. 50

What is socket.ph and where do I get it?. 50

Csharpfaq9: Networking. 50

What is the correct form of response from a CGI script?. 51

My CGI script runs from the command line but not the browser. (500 Server Error) 51

How can I get better error messages from a CGI program?. 51

How do I remove HTML from a string?. 51

How do I extract URLs?. 51

How do I download a file from the user's machine? How do I open a file on another machine?. 51

How do I make an HTML pop-up menu with C#?. 51

How do I fetch an HTML file?. 51

How do I automate an HTML form submission?. 51

How do I decode or create those %-encodings on the web?. 51

How do I redirect to another page?. 51

How do I put a password on my web pages?. 51

How do I edit my .htpasswd and .htgroup files with C#?. 51

How do I make sure users can't enter values into a form that cause my CGI script to do bad things?. 51

How do I parse a mail header?. 51

How do I decode a CGI form?. 51

How do I check a valid mail address?. 51

How do I decode a MIME/BASE64 string?. 51

How do I return the user's mail address?. 51

How do I send mail?. 51

How do I use MIME to make an attachment to a mail message?. 51

How do I read mail?. 51

How do I find out my hostname, domainname, or IP address?. 52

How do I fetch a news article or the active newsgroups?. 52

How do I fetch/put an FTP file?. 52

How can I do RPC in C#?. 52

Works Cited. 52

 

The Csharpfaq is a copy of perlfaq with questions answered in C# terms instead of perl terms. Perl has its roots in Unix and so many questions take a Mono instead of Microsoft answer approach only because Mono is the leading C# implementation on Unix. The authors wish to thank the authors of perlfaq for providing perlfaq as a perl resource. As former (and sometimes current) perl programmers we recognize that perlfaq has helped us be great perl programmers. When transitioning from perl to C# it was often easy to think in terms of perl and move that to C#. Sometimes this was a good thing, other times it was not. But rather than wade through API documentation in MSDN or Monodoc we wanted something like perlfaq.

When teaching an mentoring new perl programmers, my answer to their questions was often “That is in the perlfaq.” Or “Did look in perlfaq4?” When I started programming C# and trying to influence some of these same programmers, I noticed that they often had the same questions as they did before and that they didn’t know where to start looking for the answer. Some of the intent of Csharpfaq is to bridge this gap of information literacy. Another intent is to act as a reference for common questions. Many answers can be found in MSDN, but often diving through MSDN can be slow and difficult. Google yields many good answers to questions, but sometimes finding the right search phrase is difficult especially when namespaces are common to other languages or you are dealing with regular expressions.

Where to get the Csharpfaq?

http://workwith.net/faq/csharp/

How to contribute to the Csharpfaq?

You can mail corrections, additions, and suggestions to <csharpfaq-workers@lists.xmtp.net>.

What will happen if you mail your C# programming problems to the authors?

We will make fun of you. j/k.  Probably nothing. We might try to help. We might try to reply. We might not. We aren’t a free programming help service. More than likely we will point you to the question in the faq that most closely resembles your problem, or we will point you to MSDN documentation.

Csharpfaq1: General Questions about C#

Very general, high-level questions about C#.

What is C#?

C# is an object-oriented programming languages developed by Microsoft as part of the .NET initiative and later approved as a standard by ECMA and ISO. (C#)

Who supports C#? Who develops it? Why is it free?

Microsoft supports and develops C# via their compilers and their Visual Studio products. The C# compiler is actually available without Visual Studio or the SDK as compilation of C# code is required for ASP.NET functionality. One could also speculate that it is free because virtually all languages are free and a pay for language would greatly prohibit market share and language adoption.

Which version of C# should I usehName?

You should use the latest possible C# version that is possible in your environment.

It all depends on what you are doing. You may want to only use C# 1.0 because you are targeting the .NET framework 1.1 because it is installed by default on Windows Server 2003 and you are targeting that platform for your server or asp.net software. Alternatively you may want to use C# 3.0 because you don’t mind installing .NET framework 2.0 on your target machines. There is NOT a direct mapping from .NET framework version and C# language version.

What are C# 1, C# 2, or C# 3?

C# 1 is what shipped with .NET 1.0 and 1.1 and Visual Studio 2002 and 2003 as well as Mono 1.0. The language is well documented in the first edition of the ECMA-334 specification.

C# 2 is what shipped with .NET 2.0 and Visual Studio 2005 as well as Mono 1.2. Mono is interesting in that other than generics, they implemented the C# 2 features (e.g. anonymous delegates and events) in their 1.1 compiler. These are just compiler enhancements and can be compiled to runtime 1.0/1.1 bytecode.

C# 3 is what shipped with Visual Studio 2008. It can still target runtime version 2.0. The new language features of C# 3 are only language features and do not require new runtime features. However, the libraries which are ultimately used may only be part of libraries included with .NET 3.5. For example the extension methods for use with LINQ do not exist in framework 2.0 or 3.0. It remains to be seen if these extension methods will be in a separate redistributable assembly so that your code can use LINQ and still be distributed to target machines which only run version 2.0 of the framework.

How stable is C#?

C# is very stable. Even between major releases 1->2->3 there is very little chance of breaking source level compatibility. There is even less chance at the bytecode level (aka MSIL or CIL, not C#, but important to know). Microsoft has a very open development approach to C# including language meetings with various groups, including the Mono development teams. Microsoft is very open to feedback from the community. Open beta and CTP of Windows and .NET SDK make it easy to test upcoming versions and report compatibility problems. The result is a VERY stable language.

Is C# difficult to learn?

“No, [C#] is easy to start learning and easy to keep learning. It looks like most programming languages with which you are likely to have experience.“ (Christiansen & D'foy, 2007)

C# seems to have very few  ah-ha” moments when learning it. While C# does have its share of “devil in the details” things to know about, these seem to be edge cases. These edge cases seem to be small. The average programmer can be up and running and writing C# code in short time. As with most languages, mastering the edge cases can take quite a bit longer.

How does C# compare with other languages like Java, Python, C, C++, REXX, Scheme or Tcl?

“Favorable in some areas, unfavorably in others.” (Christiansen & D'foy, 2007)

C# is most like Java in that it compiles to a portable bytecode that is then run by a jitter to execute native code on a given platform. C# is also similar to java in that it is “object oriented”. It has no support for functions outside of a class, thus all functions are class methods.

Generics in C# are more like templates in C++. However where templates in C++ are expanded by the pre-compiler, in C# generics are known about at runtime (thus generics are a .NET runtime feature with C# language support). There is a tradeoff here. There are things that C++ templates can do that simply cannot be done with C# generics, however C# generics have this benefit of runtime awareness so it too can do things that C++ generics cannot. One biggie is that while C++ templates would create a new type for every template type, C# shares it generic type implementation for all reference types. This leads to much less code bloat.

C# is less like Python, Perl, or REXX because these are dynamic and interpreted languages. This line is definitely blurring as things like IronPython and IronRuby are released. The DLR aides in running dynamic languages on .NET. Modern Python and Ruby aren’t really interpreted anyway. These languages follow a similar compile to bytecode and then run in a managed runtime as C# does. The difference is that compilation takes place on invocation rather than before. The Dynamic Language Runtime is bridging the gap between these languages through use of the .NET runtime. While C# will probably never use or run on the DLR, you might consider using Python on DLR to interoperate with your C#.

Can I do [task] in C#?

Yes.

When shouldn’t I program in C#?

“When your manager forbids it – but consider replacing them J.” (Christiansen & D'foy, 2007)

Another answer might be: When you cannot afford the costs of a managed environment. These cases are few and you might reconsider if you think you cannot afford these costs. They are often surprisingly low. Currently even light 3d graphics is done in C# using XNA. However the latest photo-realistic 3d environment game engine is probably not well suited to be written in C#.

What’s the difference between C# and c-sharp?

I am not sure. Probably copyright. They are pronounced the same. C# is “see sharp” not “see pound” or “see number”.

Is it a C# program or a C# script?

It is a program. C# is not interpreted like Perl which will make some of the questions in this faq not make some sense. We will refer those questions to here.

I sometimes call C# programs “scripts” if they do very simple things and I’ve written them in a script style, for example, one big main method. Or complete lack of OO design. For most “scripts” OO design would be overkill” – JRW

What is a JAPH? JACH? JACSH?

“JAPH stands for ‘Just another Perl hacker’” (Christiansen & D'foy, 2007) So I guess we could coin JACH or JACSH which I pronounce as “jock” or “josh” for just another csharp hacker. I’ve never heard JACK or JACSH used so consider this term coined here.

How can I convince others to use C#?

“Appeal to their self interest!” (Christiansen & D'foy, 2007)

Csharpfaq2: Obtaining and Learning about C#

Where to find source and documentation for C#, support and related matters.

What machines support C#? Where do I get it?

The Microsoft implementation can run on x86, x86_64 and I think also Itanium.

The Mono implementation can run on many more platforms. A complete list is available here: http://www.mono-project.com/Supported_Platforms

You can get C# from Microsoft by downloading the latest .NET runtime. You probably already have some version of C# if you are running a Microsoft operating system. You can get Mono by downloading it and installing it. If you are running Linux it may be easier to use your distributions package management system to install Mono. You can download Mono here: http://www.mono-project.com/Downloads

How can I get a binary version of C#?

The Microsoft implementation is binary only and will work on supported versions of Windows. See “Where do I get it?”

The Mono download page also has precompiled versions of Mono for many supported platforms. See “Where do I get it?”

I don’t have a C compiler. How can I build my own C# compiler?

“Since you don't have a C compiler, you're doomed and your vendor should be sacrificed to the Sun gods. But that doesn't help you.” (Christiansen & D'foy, 2007)

I copied the C# compiler binary from one machine to another, but it doesn’t work.

“That's probably because you forgot libraries, or library paths differ. You really should build the whole distribution on the machine it will eventually live on…” (Christiansen & D'foy, 2007)

I grabbed the sources and tried to compile but gdbm/dynamic loading/malloc/linking/… failed. How do I make it work?

I’ll assume you are referring to Mono in which case you should read their INSTALL file and their documentation.

What modules and extensions are available for C#?

There are none for the language. The language is not extensible. This is a bad copy from the perlfaq that doesn’t match well with C#. C# has numerous free and commercial libraries available for it. There is no CPAN equivalent for C#. C# libraries are not specific to C# but will work with any .NET language. These are often called .NET libraries. Many .NET libraries will work with both Microsoft and Mono, but some are specific to one or the other. Google is your best friend in finding libraries for C#. Also see Codeplex, Sourceforge and Mono itself.

Is there an ISO or ANSI certified version of C#?

Yes as well as ECMA. But this is only the specification. There is no ISO/ANSI certified implementation. Microsoft’s implementation is the reference and everyone else seems to try to be compatible with it.

Where can I get information on C#?

There are many great books, websites, magazine articles as well as MSDN reference documentation articles.

What are the C# newsgroups on Usenet? Where do I post questions?

There aren’t any. In the mono world, try the mono developer email lists. These can be accessed via NNTP by using Gmane.

Where should I post source code?

“You should post source code to whichever group is most appropriate…” (Christiansen & D'foy, 2007)

Getting involved in any online community is a great place to learn and to have others see your code. There are many online communities around C# there is not best one. The right one for you may not be the right one for someone else.

C# Books

There are tons of C# books. Here are a few which we know to be good.

Effective C# by Bill Wagner

TODO: fill this in with recommendations.

Which magazines have C# content?

TODO: fill this in with recommendations.

What mailing lists are there for C#?

TODO: fill this in with recommendations.

http://www.mono-project.com/Mailing_Lists

Where are the archives for mono and mono-devel?

See Gmane.

Where can I buy a commercial version of C#?

Microsoft provides a commercial version of C#. You may also negotiate support for Mono and Mono’s C# through Novel.

Where do I send bug reports?

In the case of Microsoft you have to pay per incident (yes, insane, I know) AFAIK. It may be better to post to your blog or post to a Microsoft persons blog. I would go so far as to recommend you ask an MS C# MVP to investigate for you. They can often be found at your local INETA “.net user group”. If you aren’t going to those then you probably should be. Get involved in your local .NET (C#) community.

In the case of Mono you can open a bug with Ximian bugzilla. http://www.mono-project.com/Bugs

What is csharp.com, csharp-station.com, csharphelp.com, codeproject.com, etc?

TODO: put a list of good website resources here.

Csharpfaq3: Programming Tools

Programmer tools and programming support.

How do I do (anything)?

“Have you looked at CPAN (see perlfaq2)? The chances are that someone has already written a module that can solve your problem. Have you read the appropriate manpages?” (Christiansen & D'foy, 2007)

We don’t have CPAN or equivalent in the .NET (and thus C#) world. However there are still many of excellent libraries that can solve your problem. Please search before you reinvent the wheel.

How can I use C# interactively?

There have been a couple of attempts at C# interpreters but none was a full C# implementation AFAIK

Is there a C# shell?

Not that I know of. PowerShell is very different from C# and is a .NET Language of its own.

How do I find which modules/libraries are installed on my system?

Look for DLLs that are .NET assemblies. They could be anywhere on your system. The runtime has something called the Global Assembly Cache(GAC) which you may want to look at. The assemblies installed in the GAC could be considered the “installed modules” on your system. The GAC is installed in %WINDIR%\Assembly on Microsoft platforms and could be installed anywhere on a Mono platform. See your Mono distribution for more information.

How do I debug my C# programs?

Microsoft provides an excellent debugger. You don’t need to buy Visual Studio, although that is an even better debugging experience. The Microsoft CLR Debugger (DbgCLR.EXE) is part of the .NET 2.0 SDK.

Mono has a debugger. It is a console style debugger. Integration into MonoDevelop is coming soon.

How do I profile my C# programs?

Microsoft offers a profiler as a separate download. http://www.microsoft.com/downloads/details.aspx?FamilyId=A362781C-3870-43BE-8926-862B40AA0CD0&displaylang=en

Mono has a few profiling tools. http://www.mono-project.com/Profile

Google for CLR profiler or .Net profiler to find many other profiling tools.

How do I cross-reference my C# programs?

Perl has B::Xref. The Linux kernel uses LXR against its source. I know of no similar tools for C#. However, C# does have a standard for inline comment documentation. The C# compiler must output XML based on this comment documentation.

See Annex E of ECMA-334 and http://msdn.microsoft.com/msdnmag/issues/02/06/XMLC/

Is there a pretty-printer (formatter) for C#?

Visual studio does a pretty nice job of pretty printing C#. The Copy-As-Html Visual Studio add-in is also very useful. GNU enscript and Highlight can both pretty-print C#. Although GNU enscript doesn’t include the provider it is available here: http://wiki.hasno.info/index.php/Csharp.st

Is there a ctags for C#?

Yes, Exuberant ctags (http://ctags.sourceforge.net) has support for C#.

Is there an IDE or Windows C# editor?

Visual Studio is the most popular IDE for C#. There is C# support in countless other editors. Gvim has good support. Notepad2 has good support. SharpDevelop is a open source IDE for .NET that runs on Windows. MonoDevelop is an open source IDE for .NET that runs on Linux.

Where can I get C# macros for vi?

Gvim ships with “cs” syntax highlighting, indent, and and file type support.

Where can I get csharp-mode for emacs?

http://www.emacswiki.org/cgi-bin/wiki/CSharpMode

How can I use curses with C#?

http://www.mono-project.com/MonoCurses

How can I use X or Tk with C#?

http://www.mono-project.com/Gtk

I know of no wait to use the antiquated “tk” with C# or Mono.

How can I make my C# program run faster?

http://www.mono-project.com/Performance_Tips

While this is mono documentation, nearly all of the concepts hold true for the MS runtime.

How can I make my C# program take less memory?

http://www.mono-project.com/Performance_Tips

While this is mono documentation, nearly all of the concepts hold true for the MS runtime.

Is it safe to return a reference to a local or lexical data?

This question is a bit of loaded perl, but it does have come C# corresponding questions. In a CLR there are reference types and there are value types. You can return a reference to a local, because the runtime is a garbage collected environment.

“Yes. Perl's garbage collection system takes care of this so everything works out right.” (Christiansen & D'foy, 2007)

How can I free an array or hash so my program shrinks?

“You usually can't.” (Christiansen & D'foy, 2007)

999 times out of a thousand you don’t need to do this. There is much writing on how and why to NEVER call GC.Collect(). Please use google and read about GC.Collect(). If you need this level of memory management, any managed environment is probably not right for you.

How can I make my CGI script more efficient?

CGI in C#? Well, it isn’t impossible. CGI is a gateway to ANY program. But with ASP.NET, CGI is not really used with C#. So the answer is: use ASP.NET

How can I hide the source for my C# program?

“Delete it. :-) Seriously, there are a number of (mostly unsatisfactory) solutions with varying levels of "security".” (Christiansen & D'foy, 2007)

It is true in perl and it is true in C# or any .Net program. See Lutz Roder’s Reflector program or even Mono’s monodis program.

How can I compile my C# program into byte code or C?

“In general, you can't do this.” (Christiansen & D'foy, 2007)

Runtime executed code is already byte code compiled.

How can I get #!/usr/bin/csharp to work on [MS-DOS, NT, … ] ?

C# is not perl J This is a bad copy from the perlfaq that doesn’t match well with C#.

C# programs compile to .NET bytecode. Windows operating systems know how to execute these .NET assemblies. They are .EXE files. In Linux you can help along these binary types by using [TODO: document that Linux file helper]

But most Mono programs simply create shell script wrappers for the compiled .exe files. E.g. ~/bin/MyProgram.exe has a shell script wrapper called ~/bin/MyProgram with contents “mono MyProgram.exe”.

Can I write useful C# programs on the command line?

Not really. Certainly not like you can write one liners in perl.

Why don’t C# one-liners work on my DOS/Mac/VMS system?

See the previous question.

Where can I learn about CGI or Web programming in C#?

www.asp.net is a portal page run by Microsoft which is a great starting point for C# web programming. CastleProject has MonoRail which is an alternative to the WebForms style of ASP.NET Web development. Mono has some ASP.NET documentation http://www.mono-project.com/ASP.NET

Where can I learn about object-oriented C# programming?

See books, magazines, mailing lists, tutorials and websites.

Where can I learn about linking C with C#?

P/Invoke is well documented by Microsoft and Mono.

There is also a very interesting Mono project called “linker”. http://www.mono-project.com/Linker

I’ve read XYZ but I can’t embed C# in my C program; what am I doing wrong?

I’ll assume this is in regard to Mono. I know of no way to do this with the Microsoft runtime.

http://www.mono-project.com/Embedding_Mono

When I tried to run my script, I got this message. What does it mean?

I’ll assume this is a compile time question. The compiler usually gives very good messages. If you can’t understand them, then you should probably read more.

There are some exceptions. http://weblogs.asp.net/avnerk/archive/2006/05/22/Bad-compiler-warnings-when-using-anonymous-methods-for-Predicate_3C00_T_3E00_.aspx

"cannot convert from 'anonymous method' to 'System.Predicate<Whatever>'" is sometimes displayed when the anonymous method doesn’t have the correct return type. Make sure all code paths of the anonymous method return the same type.

What’s MakeMaker? [x:What is MSBUILD or Nant?]

C# programs are usually distributed with either a Makefile, or a MSBUILD csproj or sln file, or a nant build script.

Csharpfaq4: Data Manipulation

Manipulating numbers, dates, strings, arrays, hashes, and miscellaneous data issues.

Everything I learned about perl I learned from perlfaq4 – JRW

Data: Numbers

Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?

“Internally, your computer represents floating-point numbers in binary. Digital (as in powers of two) computers cannot store all numbers exactly. Some real numbers lose precision in the process. This is a problem with how computers store numbers and affects all computer languages, not just Perl.” (Christiansen & D'foy, 2007)

Why is int() broken?

Your int() is most probably working just fine. It's the numbers that aren't quite what you think.

First, see the answer to "Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?".

 (Christiansen & D'foy, 2007)

Why isn’t my octal data interpreted correctly?

The C# language standard does not support octal characters constants by default.

Does C# have a round() function? What about ciel() and floor()? Trig functions?

The Math class in the System namespace has Round(), Ceiling() and Floor(). There are many overloads which allow setting precision.

The same Math class has common trig functions such as Sin(), Cos(), Tan(), Abs(), Asin(), Acos(), Atan(), Atan2(), Exp(), Log(), Pow(), Log10(), Sinh(), Cosh() and Tanh().

How do I convert between numeric representations/bases/radixes?

There are lots of ways. You could reference the Microsoft.VisualBasic assembly and use the Conversion class. You could use the Parse method available on many of the base types and use its NumberStyles overload. You may even be able to use System.Convert class to help you do it.

How do I convert hexadecimal into decimal?

The C# language standard does not support octal or hexadecimal characters constants by default. The class methods given here will work in any .Net language.

string num = “A”;

int val = int.Parse(num, NumberStyles.HexNumber);

Console.WriteLine(“{0} in hex = {1} in decimal”, num, val );

// A in hex = 10 in decimal.

 

MSDN Topic titled “Parsing Numeric Strings” is a good source of more information.

How do I convert from decimal to hexadecimal?

int num = 10;

Console.WriteLine(“{0} in hex = {1} in decimal”, num.ToString(“X”), num);

// A in hex = 10 in decimal.

 

MSDN topic titled “Standard Numeric Format Strings” is a good source of more information.

How do I convert from octal to decimal

 

How do I convert from decimal to octal

How do I convert from binary to decimal

How do I convert from decimal to binary

Why doesn’t & work the way I want it to?

This is the bitwise and operator. If you want a logical and, use &&. If you are looking to reference a memory location then you should have probably used a reference type. C# will automatically box and unbox value types. For more information on boxing see “Boxing and Unboxing” in the C# Programming Guide.

If you are writing unsafe code then & can function as the “address of” operator. If you are writing unsafe code you should be experienced enough to NOT need this reference.

How do I multiply matrices?

System.Drawing.Drawing2D.Matrix in the System.Drawing assembly provides support for 3-by-3 matrices. (from GDI+)

System.Windows.Media in WindowsBase assembly (from WPF) also provides support for 3-by-3 matrices.

System.Windows.Media.Media3D.Matrix3D in the PresentationCore assembly (from WPF) provides support for 4x4 matrix used for transformations in 3-D space.

A google search for C# matrix yields many interesting general purpose Matrix implementations.

http://www.codeproject.com/csharp/rtwmatrix.asp

A commercial general matrix library is available from bluebit software: http://www.bluebit.gr/NET/

How do I perform an operation on a series of integers?

To call a function on each element in an array and collect the results use;

int[] results = Array.ForEach<int> ( myIntArray, MyFunc );

For example:

int[] triple = Array.ForEach<int> ( single, (x) => x*3 );

But that example uses C# 3.0’s lambda features. As long as we are using C# 3.0 we may as well use LINQ.

int[] triple = (from s in single select s*3).ToArray();

But most people are still using C# 2.0, so let’s turn that above lambda back into an anonymous delegate.

int[] triple = Array.ForEach<int> ( single, delegate(int x) { return x*3; });

If you happen to still be using C# 1.0, then it becomes more than one line of code. There are no generics, there are no anonymous delegates.

int[] triple = new int[single.Length];

for( int i = 0 ; i<single.Length ; i++ ) { triple[i] = single[i]*3; }

To call a function on each element of an array, but ignore the results:

foreach( object o in array ) { some_func(o); } 

although you should probably specify a strong type instead of object.

To call a function on each integer in a (small) range, you can use:

 

How can I output Roman numerals?

Why aren’t my random numbers random?

Computers are good at being predictable and bad at being random (despite appearances caused by bugs in your programs :-). (Christiansen & D'foy, 2007)

You can seed System.Random by passing a value to the constructor, or you can use RNGCryptoServiceProvider instead. The interface for RNGCryptoServiceProvider is not the same as System.Random so your code may need changing. Better yet, use adapter pattern to create a compatible interface that gets its random numbers from RNGCryptoServiceProvider.

How do I get a random number between X and Y?

System.Random.Next() has an overload that takes minValue and maxValue as a parameter. This returns an int.  System.Random.NextDouble() returns a double from 0 to 1. If you want a double between X and Y you will need to do the math yourself. For example for a double between 1.5 and 4.5

double myNumber = 1.5 + (new System.Random()).NextDouble() * (4.5-1.5);

Data: Dates

How do I find the day or week of the year?

DateTime has DayOfWeek and DayOfYear properties.

DateTime now = DateTime.Now;

Console.WriteLine(“Today is {0} and it is the {1} day of the year”, now.DayOfWeek, now.DayOfYear);

How do I find the current century or millennium?

Divide DateTime.Year by 100 or 1000 +1

DateTime now = DateTime.Now;

Console.WriteLine(“Today we live in Century {0} and Millenium {1}”, now.Year/100 + 1, now.Year/1000 +1);

How can I compare two dates and find the difference?

Use the subtract or overloaded minus operator. This will give a result of type TimeSpan. You can also subtract a TimeSpan from a DateTime to find another DateTime.

DateTime now = DateTime.Now;

DateTime Christmas = new DateTime( now.Year, 12, 25 );

TimeSpan threedays =  new TimeSpan(3,0,0,0);

Console.WriteLine(“Three days ago was {0}”, now - threedays );

Console.WriteLine(“There is {0} until Christmas”, Christmas - now );

How can I take a string and turn it into epoch seconds?

DateTime as a Parse method (like most .NET primitives).

string myDateTimeStr = “04/17/2007 14:30:00”;

DateTime myDateTime = DateTime.Parse(myDateTimeStr);

DateTime epoch = new DateTime(1970,1,1);

(myDateTime – epoch).TotalSeconds

 

How can I find the Julian Day?

http://www.codeproject.com/csharp/JalaliCalendar.asp

http://heybo.com/weblog/posts/254.aspx

Calculate the Julian Date

(DateTime.UtcNowDateTime.MinValue).TotalDays + (DateTime(4713,1,1)-DateTime(1,1,1)).TotalDays +403

Or the modified Julian Date

(DateTime.UtcNow – new DateTime(1858,11,17)).TotalDays

Or the day of the year (which is what some people think of as Julian day)

(new System.Globalization.JulianCalendar()).GetDayOfYear(DateTime.Now);

How do I find yesterday’s date?

DateTime.Now.AddDays(1)

Does C# have a Year 2000 problem? Is C# Y2K compliant?

.NET does not have a Year 2000 problem. It is Y2K compliant. C# compiles to bytecode on .NET and thus does not have a Yeark 2000 problem and is Y2K compliant.

Data: Strings

How do I validate input?

There are many ways. CastleProject has a Validation system which works well with MonoRail. EnterpriseLibrary from Microsoft had a Validation system.

How do I unescape a string?

It depends on what you mean. URL and Html escapes can be handled with HttpUtility class in System.Web namespace and assembly.

How do I remove consecutive pairs of characters?

You can use the substitution operator to find pairs of characters (or runs of characters) and replace them with a single instance. In this substitution, we find a character in (.). The memory parentheses store the matched character in the back-reference \1 and we use that to require that the same thing immediately follow it. We replace that part of the string with the character in $1. (Christiansen & D'foy, 2007)

/* s/(.)\1/$1/g; #is the perl regex */

string stripped = (new Regex(@“(.)\1”)).Replace(“Haarlem”,”$1”);

Here is the same example as perlfaq converting Haarlem like in the Netherlands to Harlem like in New York.

How do I expand function calls in a string?

There have been a number of attempts at a “exec” method for C# that uses CodeDom. I have not seen any one that did a very great job. C# is compiled to bytecode and then executed by a JIT engine. The method or function call you wish to perform may not exist at runtime.

How do I find matching/nesting anything?

This isn't something that can be done in one regular expression, no matter how complicated. (Christiansen & D'foy, 2007)

A regular expression is a representation of a Regular Language in the field of formal languages. They are equivalent to finite automaton. It can be proven that this is impossible. This is the task of a regular grammar.

How do I reverse a string?

Array.Reverse will reverse an array in place.

string mystring = “hello”;

char[] mystringCharArr = mystring.ToCharArray()

Array.Reverse(mystringCharArr)

string reverse = new string ( mystringCharArr );

How do I expand tabs in a string?

string tabSpaces = new string(“ “,4);

string expanded = (new Regex(@”\t”)).Replace(mystring, tabSpaces);

How do I reformat a paragraph?

[TODO: find a Text::Wrap and Text::Autoformat .NET Library or C# code]

How can I access or change N characters of a string?

Access can be done for a single character using the indexer in C#.

string x = “things”;

char I = x[2];

 

Strings in .NET are immutable reference types so any change results in the creation of a new string.

string jacsh = “Just another C-sharp hacker”;

string jacsh = jacsh.Substring(0,20) + “ 3.0 “ + jacsh.Substring(22,6);

// Just another C-sharp 3.0 hacker

 

How do I change the Nth occurrence of something?

You have to keep track of N yourself. (Christiansen & D'foy, 2007)

int want = 3;

string sues = “One fish two fish red fish blue fish”;

Regex fisher = new Regex(@”(\w+)\s+fish\b”, RegexOptions.IgnoreCase );

int count = 0;

foreach (Match match in fisher.Matches(sues)) {

      count++;

      if ( count == 3 ) {

           Console.WriteLine(“the third fish is a {0} one.”, match.Group[1] );

      }

}

How can I count the number of occurrences of a substring within a string?

int count = 0;

while( -1 != mystring.Count(“x in mystring”) )

      count ++;

string.Count has overrides for Char and string and other overrides.

How do I capitalize all the words on one line?

.NET regular expressions don’t support the \L \U modifiers like perl does. However, .NET provides a MatchEvaluator delegate which lets you call code for every match in a regular expression.

string title = Regex.Replace("welcome to the csharpfaq", @"\b(\w)",

delegate(Match m) { return m.Groups[1].Value.ToUpper(); });

Console.WriteLine(title);

To make the whole string uppercase just use string.ToUpper

string upper = somestring.ToUpper();

You can (and probably should) enable locale awareness of those characters by using the CultureInfo overload

str2 = str1.ToUpper(new CultureInfo("en-US", false));

There is also System.Globalization.TextInfo.ToTitleCase()

TextInfo myTI = new CultureInfo(“en-US”,false).TextInfo;

string title = myTI.ToTitleCase(“welcome to the csharpfaq”);

 

How can I split a [character] delimited string except when inside [character]?

Usually characters here are a comma and a quote. ODBC allows the use of an ODBC ADO.NET CSV DataProvider. There are multiple CSV parsers available at places like CodeProject.

Take the example case of trying to split a string that is comma-separated into its different fields. You can't use split(/,/) because you shouldn't split if the comma is inside quotes. For example, take a data line like this:

      SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped"

Due to the restriction of the quotes, this is a fairly complex problem. Thankfully, we have Jeffrey Friedl, author of Mastering Regular Expressions, to handle these for us. He suggests (assuming your string is contained in $text):

       @new = ();

       push(@new, $+) while $text =~ m{

            "([^\"\\]*(?:\\.[^\"\\]*)*)",?  # groups the phrase inside the quotes

           | ([^,]+),?

           | ,

           }gx;

       push(@new, undef) if substr($text,-1,1) eq ',';

If you want to represent quotation marks inside a quotation-mark-delimited field, escape them with backslashes (eg, "like \"this\"". (Christiansen & D'foy, 2007)

This is Csharpfaq so you may or may not know perl. The above is a rather nice regular expression. We can get similar behavior with C# using this code.

string text = "\"This is a Quoted Value\",1,2,CSV,omg csv,\"Quotes, commas, and things\"";

Console.WriteLine(text);

List<string> values = new List<string>();

//+        re    {"([^"\]*(?:\.[^"\]*)*)",? | ([^,]+),? | ,}    System.Text.RegularExpressions.Regex

Regex re = new Regex(

    "\"([^\\\"\\]*(?:\\.[^\\\"\\]*)*)\",?" + // groups the phrase inside the quotes

@"|([^,]+),?" +

@"|,"     , RegexOptions.None);

 

foreach (Match m in re.Matches(text))

{

    values.Add(m.Groups[m.Groups.Count - 1].Value);

}

[TODO: this regex doesn’t work fix this!]

 

How do I strip blank space from the beginning/end of a string?

Use string.Trim(), string.TrimEnd(‘ ‘), string.TrimStart(‘ ‘);

How do I pad a string with blanks or pad a number with zeroes?

Use the String(Char, Int32) constructor.

string things = new string(‘ ‘, 20) + “my stuff”;

How do I extract selected columns from a string?

If you know where the columsn that contain the data are, you can use string.Substring to extract a single column

string column = line.Substring(startColumn, length);

 

You can use split if the columns are separated by whitespace or some other delimiter as long as the delimiter cannot appear as part of the data.

string line = “ fred barney   betty   “;

string[] columns = line.Split(‘ ‘);

// { “”, “fred”, “barney”, “”, “”, “betty”, “”, “”

How do I find the soundex value of a string?

[TODO: what is soundex?]  Is this a good place for Levenshtein distance from http://www.merriampark.com/ldcsharp.htm

How can I expand variables in text strings?

If you can avoid it, don’t, or if you can use a templating system, such as NVelocity, do that instead.

String.Format allows you do insert text strings.

String foo = “Fred”;

String bar = “Barney”;

String hello = string.Format(“Say hello to {0} and {1}” foo, bar);

What's wrong with always quoting "$vars"?

With C# you can’t do that, so it doesn’t apply. However the string class is often misunderstood. People say not to use + and to prefer string.Format. It turns out that the compiler itself has some optimizations for using + concatenation. Don’t prematurely optimize strings. You should just be aware that they are immutable reference types with value semantics. If you run into issues, then you can consider optimizing.

http://www.ayende.com/Blog/archive/2007/07/06/The-truth-about-string-concatenation-performance.aspx

Why don't my <<HERE documents work?

With C# you can’t do that either!  :0

Data: Arrays

What is the difference between a list and an array?

This is VERY different than perl, so beware. In .NET arrays are more like C arrays. They are fixed length at time of creation. They represent a contiguous block of memory. Lists are anything that implements IList. Usually this is System.Collections.ArrayList or System.Collections.Generic.List<>

The generic List<> should almost always be preferred to use of ArrayList.

Array’s have a Length property. Lists have a Count property.

What is the difference between $array[1] and @array[1]?

C# doesn’t have these language issues.

How can I remove duplicate elements from a list or array?

Use a Dictionary (hash). When you think the words “unique” or “duplicated”, think Dictionary keys.

If you don’t care about the order of the elements, you could just create the Dictionary and then extract eh keys.

string[] words = { "one", "two", "three", "one", "four" };

Dictionary<string, bool> dict = new Dictionary<string, bool>();

Array.ForEach(words, delegate(string s) { dict[s]= true; });

How can I tell whether a certain element is contained in a list or array?

Hearing the word "in" is an indication that you probably should have used a hash, not a list or array, to store your data. Hashes are designed to answer this question quickly and efficiently. Arrays aren't. (Christiansen & D'foy, 2007)

Both Array and List have an Exists method. List also has a Contains method.

List<string> goodcolors = new List<string>( new string[] { "Red", "White", "Blue" });

string[] okcolors = { "Teal", "Pink" };

bool contains = goodcolors.Contains("Red");

Console.WriteLine(contains);

contains = Array.Exists(okcolors, delegate(string s)

{

    if (s == "Teal")

    {

        return true;

    }

    else

    {

        return true;

    }

});

Console.WriteLine(contains);

return contains;

How do I compute the difference of two arrays? How do I compute the intersection of two arrays?

Use a hash. (Are you seeing a theme here?)

This assumes that each element is unique in a given List/Array. Since both are enumerable, one and two in the example below could be either Lists or Arrays.

List<string> one;

string[] two;

GetListAndArray(out one, out two);

List<string> union = new List<string>(), intersection = new List<string>(), difference = new List<string>();

Dictionary<string, int> count = new Dictionary<string, int>();

foreach (string element in one)

    if (count.ContainsKey(element) ) count[element]++;

    else count[element] = 1;

foreach (string element in two)

    if (count.ContainsKey(element)) count[element]++;

    else count[element] = 1;

foreach (string element in count.Keys)

{

    union.Add(element);

    (count[element] > 1 ? intersection : difference).Add(element);

}

Console.WriteLine("union:"+ string.Join(", ",union.ToArray()));

Console.WriteLine("intersection:" + string.Join(", ", intersection.ToArray()));

Console.WriteLine("difference:" + string.Join(", ", difference.ToArray()));

 

[TODO: implement this again using C# 3.0.  New IEnumberable members and Queryable members may make this more readable.]

See also C5 Collections for a real Set implementation. http://www.itu.dk/research/c5/

How do I test whether two arrays or hashes are equal?

It depends on what you mean by equal. Reference equality should be easy enough, just compare the two.

Lists by definition are ordered. If you want an unordered comparison you should be able to simply check that the two lists have the same number of Count and Contains for each element in the list.

So for lists:

List<int> one = new List<int>(new int[] { 1, 2, 3 });

List<int> two = new List<int>(new int[] { 1, 2, 3 });

if (one.Count != two.Count)

    return false;

foreach (int element in one)

    if (!two.Contains(element))

        return false;

return true;

 

Or for an array:

int[] a = new int[] { 1, 2, 3 };

int[] b = new int[] { 1, 2, 3 };

foreach (int element in a)

    if (!Array.Exists(b, delegate(int i) { return i == element; }))

        return false;

return true;

If you want to compare ordered arrays or lists just sort first and use the above.

If you want to compare whether two dictionaries are equal, compare their key Lists just as above and if that is true, then compare values at each key.

Dictionary<string, string> one = GetSomeDictionary();

Dictionary<string, string> two = GetSomeOtherDictionary();

if (one.Count != two.Count)

    return false;

foreach (string element in one.Keys)

if (!two.ContainsKey(element) || two[element] != one[element])

           return false;

return true;

 

How do I find the first array element for which a condition is true?

Use Array.Find.

int found = Array.Find(arrayOfInt, delegate(int i) { return 4 == i; });

If you want to Filter you can use Array.FindAll with the exact same predicate delegate but the return type is array.

If you want to do the same thing for a List you can use a very similar Find or FindAll, but they are not static methods:

listOfInt.Find(delegate(int i) { return 4 == i; });

 

Of course C# 3.0 has lambdas and extension methods. The extension method means you can do this for either Array or List:

enumerableInt.Find( i =>  4 == i );

 

If you have C# 3.0 then you have LINQ. LINQ allows this to be written as:

(from i in enumerableInt where i=4 select i).Take(1).ToList()[0];

 

Or the FindAll version:

from i in enumerableInt where i=4 select i;

 

Array.Find and List.Find returns default value for the type if nothing is found. It may make sense to cast to nullable to return null in the case of something not being found.

How do I handle linked lists?

Don’t. Just use List<>. See also C5. http://www.itu.dk/research/c5/

How do I handle circular lists?

Don’t. Just use List<>. See also C5. http://www.itu.dk/research/c5/

How do I shuffle an array randomly?

Implement IComparer with a random based implementation like this:

public class RandomComparer:System.Collections.IComparer

{

    Random random;

    public RandomComparer()

    {

        random = new Random();

    }

    #region IComparer Members

    public int Compare(object x, object y)

    {

        return random.Next(3) - 1;

    }

    #endregion

}

Then use Array.Sort and pass it this comparer.

int[] arrayOfInt = { 1, 2, 3, 4, 5, 9, 8, 7, 6 };

Array.Sort(arrayOfInt, new RandomComparer());

 

This works great for Arrays and the old weakly typed collections like ArrayList, but for Generic List you need a Generic IComparer. You can achieve this with simple inheritance of the non-generic type and implementing the generic interface.

public class RandomComparer:System.Collections.IComparer

{

    Random random;

    public RandomComparer()

    {

        random = new Random();

    }

    #region IComparer Members

    public int Compare(object x, object y)

    {

        return random.Next(3) - 1;

    }

    int IComparer.Compare(object x, object y)

    {

        return random.Next(3) - 1;

    }

    #endregion

}

public class RandomComparer<T> : RandomComparer, IComparer<T>

{

    #region IComparer<T> Members

    public int Compare(T x, T y)

    {

        return ((IComparer) this).Compare(x, y);

    }

    #endregion

}

Then use list.Sort and pass it the generic comparer.

List<int> listOfInt = new List<int>(arrayOfInt);

listOfInt.Sort(new RandomComparer<int>());

How do I process/modify each element of an array?

Use foreach. See many above previous examples.

Or you can use Array.ForEach or List<T>.ForEach. Again, see many of the above previous uses.

In C# 3.0 you can also use LINQ. This was seen previously in the answer to “How do I find the first array element for which a condition is true?

How do I select a random element from an array?

Random random = new Random();

myArray[random.Next(myArray.Length)];

For a list do the exact same thing but use Count instead of Length.

How do I permute N elements of a list?

[TODO: Find an efficient permutation algorithm.]

How do I sort an array by (anything)?

See the question “How do I shuffle an array randomly?” Implement IComparer and IComparer<T> but this time actually compare the incoming values and return -1, 0 or 1 depending on what sort order you want.

How do I manipulate arrays of bits?

See the BitArray and BitConverter classes. [TODO: give some examples here]

Why does defined() return true on empty arrays and hashes?

C# doesn’t have silly perlisms like this.

Data: Hashes (Associative Arrays) [x:Dictionaries]

How do I process an entire hash?

What happens if I add or remove keys from a hash while iterating over it?

How do I look up a hash element by value?

How can I know how many entries are in a hash?

How do I sort a hash (optionally by value instead of key)?

How can I always keep my hash sorted?

What's the difference between "delete" and "undef" with hashes?

Why don't my tied hashes make the defined/exists distinction?

How do I reset an each() operation part-way through?

How can I get the unique keys from two hashes?

How can I store a multidimensional array in a DBM file?

How can I make my hash remember the order I put elements into it?

Why does passing a subroutine an undefined element in a hash create it?

How can I make the C# equivalent of a C structure/C++ class/hash or array of hashes or arrays?

How can I use a reference as a hash key?

Data: Misc

How do I handle binary data correctly?

You just do. C# has no issues. Since C# was developed my Microsoft you don’t have to use binmode like in Perl or +b like in Python when opening your files. Just open your files and read you data.

How do I determine whether a scalar is a number/whole/integer/float?

C# is not Perl. C# has types for each of these. If you are reading from a string and into a type you may be able to use regular expressions just like in perl.

if(Regex.IsMatch(myStr,@”\D”))

{ Console.WriteLine(“has nondigits”); }

if(Regex.IsMatch(myStr,@”^\d+$”))

{ Console.WriteLine(“is a whole number”); }

if(Regex.IsMatch(myStr,@”^-?\d+$”))

{ Console.WriteLine(“is an integer”); }

if(Regex.IsMatch(myStr,@”^[+-}?\d+$”))

{ Console.WriteLine(“is a +/- integer”); }

if(Regex.IsMatch(myStr,@”^-?\d+\.?\d*$”))

{ Console.WriteLine(“is a real number”); }

if(Regex.IsMatch(myStr,@”^-?(?:\d+(?:\.\d*)?|\.\d+)$”))

{ Console.WriteLine(“is a decimal number”); }

if(Regex.IsMatch(myStr,@”^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$”))

{ Console.WriteLine(“a C float”); }

Ideally you will know what datatype you are expecting to read, or you will be able to use the lowest common type, like using double even though you may read an integer number.

How do I keep persistent data across program calls?

Perl cites DBM. In the .NET world objects can be Serializable. They can serialize either to Binary or to XML. The same object can be Serializable to either of these. You can implement your own serialization routines.

XmlSerializer serializer = new XmlSerializer( typeof ( MyType ) );

using ( TextWriter writer = new StreamWriter( “MyType.xml” ) )

{

      serializer.Serialize( writer, instanceOfMyType );

}

Or binary Serialization to Deserialize:

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters.Binary;

MyType foo;

using ( Stream stream = new FileStream(“somefile.dat” FileMode.Open, FileAccess.Read, FileShare.Read) )

{

      foo = (MyType) (new BinaryFormatter()).Deserialize(stream);

}

How do I print out or copy a recursive data structure?

Do it manually.

How do I define methods for every class/object?

C# 3.0 has Extension methods that could enable you to do this. Previous versions of C# has no means to do this.

How do I verify a credit card checksum?

[TODO: Find or implement a C# version of Business::CreditCard]

How do I pack arrays of doubles or floats for XS code?

XS is an interface description file format used to create an extension interface between Perl and C.  .NET has the concept of P/Invoke. Doubles, floats, and arrays of them should marshall just fine via P/Invoke.

Csharpfaq5: Files and Formats

I/O and the “f” issues: filehandles, flushing, formats, and footers.

How do I flush/unbuffer an output filehandle? Why must I do this?

[TODO: I don’t know much about how .NET at the console or with file IO does writes compared to stdio]

Nearly all IO operations are performed by some class that inherits from Stream. Stream has a Flush method which can be called to flush the stream.

How do I change, delete, or insert a line in a file, or append to the beginning of a file?

Just like perl, .Net doesn’t provide random access to lines. Some libraries might be able to fake this.

A C# program to do these tasks takes the basic form of opening a file, printing its lines, then closing the file:

using (StreamWriter outStream = new StreamWriter("outfile"))

using (StreamReader inStream = new StreamReader("inputfile"))

{

    string line;

      while( ( line = inStream.ReadLine() ) != null )

    {

      outStream.WriteLine(line);

    }

}

With this basic form, add the parts that you need to inset, change, or delete lines.

To prepend lines to the beginning, print those lines before you enter the loop that prints the existing lines.

using (StreamWriter outStream = new StreamWriter("outfile"))

using (StreamReader inStream = new StreamReader("inputfile"))

{

    string line;

      outStream.WriteLine(“#Add this line to the top”);

while( ( line = inStream.ReadLine() ) != null )

    {

      outStream.WriteLine(line);

    }

}

To change existing lines, insert the code to modify the lines inside the while loop. In this case, the code finds all lowercased versions of “csharp” and uppercases them. This happens on every line so make sure you wanted to do it on every line.

using (StreamWriter outStream = new StreamWriter("outfile"))

using (StreamReader inStream = new StreamReader("inputfile"))

{

    string line;

      outStream.WriteLine(“#Add this line to the top”);

while( ( line = inStream.ReadLine() ) != null )

    {

      line = line.Replace(“csharp”,”CSHARP”);

      outStream.WriteLine(line);

    }

}

To change only a particular line, the input line number is useful. Unlike perl and its $., you have to keep track of the input line number yourself.

using (StreamWriter outStream = new StreamWriter("outfile"))

using (StreamReader inStream = new StreamReader("inputfile"))

{

    string line;

      outStream.WriteLine(“#Add this line to the top”);

      int lineNumber=0;

while( ( line = inStream.ReadLine() ) != null )

    {

      lineNumber++;

      if(lineNumber==4)

           line = line.Replace(“things”, “stuff”);

      outStream.WriteLine(line);

    }

}

To skip lines, use the looping controls. The continue statement in C# is the same as next statement in perl. The break statement in C# is the same as last in perl. The continue statement ends execution of the while block for this iteration and continues on to the next iteration.

using (StreamWriter outStream = new StreamWriter("outfile"))

using (StreamReader inStream = new StreamReader("inputfile"))

{

    string line;

      outStream.WriteLine(“#Add this line to the top”);

while( ( line = inStream.ReadLine() ) != null )

    {

      if (line.StartsWith(“#”)) continue;

      if (Regex.IsMatch(line, “^__(END|DATA)__$”)) break;

      outStream.WriteLine(line);

    }

}

To do the same sort of thing to delete a particular line by using continue to skip the lines you don’t want in the output. This example skips every fifth line.

using (StreamWriter outStream = new StreamWriter("outfile"))

using (StreamReader inStream = new StreamReader("inputfile"))

{

    string line;

      outStream.WriteLine(“#Add this line to the top”);

      int lineNumber=0;

while( ( line = inStream.ReadLine() ) != null )

    {

      lineNumber++;

      if((lineNumber % 5)==0)

           outStream.WriteLine(line);

    }

}

 

StreamReader has a ReadAll() method, but it does not read the file into an array of strings based on line separators like perl’s arrary=filehandle syntax. Use the above method to populate a List<string> if you want to read the whole file at once. This should be avoided for anything but the smallest files to prevent using too much memory.

Perl oneliners using perl –pi –e and perlni –e are very convenient. C# is not perl. Keep a copy of perl around for these handy oneliners.

How do I count the number of lines in a file?

Count the newlines in the file.

using (StreamReader inStream = new StreamReader("inputfile"))

{

string line;

int lineNumber=0;

while( ( line = inStream.ReadLine() ) != null )

lineNumber++;

}

 

Or you could use ReadAll() and a regex to count the newlines.

using (StreamReader inStream = new StreamReader("inputfile"))

  int lines=Regex.Match(inStream.ReadAll(),Environment.NewLine).Count;

 

How can I use Perl's -i option from within a C# program?

You can’t.

You can implement it yourself.

/// <summary>

/// Rotates the files based on RotateCopies member.

/// This is typically used by helper functions.

/// </summary>

/// <param name="sourcefile">Sourcefile.</param>

/// <param name="destfile">Destfile.</param>

private static void RotateFiles(string sourcefile, string destfile, int CopiesToSave)

{

    while ( -- CopiesToSave >= 1 )

        RotateAway(destfile, CopiesToSave);

    if ( File.Exists( destfile ) )

        File.Move(destfile,destfile+".1");

    if ( File.Exists(sourcefile) )

        File.Copy(sourcefile,   destfile);

}

/// <summary>

/// Rotates the file.  This is the iterative helper to Rotate Fi

les.

/// </summary>

/// <param name="oldfile">Oldfile.</param>

/// <param name="ext">Ext.</param>

private static void RotateAway (string oldfile, int ext)

{

    if ( File.Exists(oldfile + "." + (ext+1).ToString()) )

        File.Delete(oldfile + "." + (ext+1).ToString());

    if ( File.Exists(oldfile + "." + ext.ToString()) )

        File.Move(oldfile + "." + (ext).ToString(),oldfile + "." + (ext+1).ToString());

}

 

How can I copy a file?

File.Copy in System.IO namespace takes a source and destination.

How do I make a temporary file name?

Path.GetTempFileName in System.IO

How can I manipulate fixed-record-length files?

It pure .NET code (no external libraries) you would have to use BinaryReader and BinaryWriter directly for binary files or just read the fixed length text records if they are text files.

Perl (and python and many others) have a couple of functions call pack and unpack where the format of a binary record can be specified using a template. See perldoc –f pack and perldoc –f unpack for details on these perl methods.

Mono implements Pack and Unpack in a library called Mono DataConvert. It is a replacement for System.BitConvert. See http://www.mono-project.com/Mono_DataConvert for more info.

How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles?

C# doesn’t use filehandles like Perl and C. In .NET a stream is just another instance of an object. They are local, or class members or whatever you scope them to. You can pass them. You can make arrays of them. They are not special.

How can I use a filehandle indirectly?

See How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles?

How can I set up a footer format to be used with write()?

I don’t even know what this means, and the perlfaq doesn’t even answer this question very well.

If you want a footer it sounds like you are doing form template type stuff. Try NVelocity.

How can I write() into a string?

Try string.Format().

How can I output my numbers with commas added?

int.ToString() has an overload that accepts a string and an IFormatProvider. You probably don’t need the IFormatProvider because you should use your systems current culture. The format string value “N” is most general for a general number.

int x = 1234567890;

Console.WriteLine( x.ToString(“N”) ); // 1,234,567,890

How can I translate tildes (~) in a filename?

You can’t. Most systems don’t really do that either. Your unix shell does that. Perl has a glob operator that can expand ~.

For ASP.NET websites ~ often means the current SiteRoot. You can use HttpUtility methods to expand the path.

How come when I open a file read-write it wipes it out?

You are opening with FileMode.Create when you probably really want FileMode.Append and then to seek. Or you can open file FileMode.Open and FileAccess.ReadWrite.

Why do I sometimes get an "Argument list too long" when I use <*>?

You don’t, because .NET is not perl J

Is there a leak/bug in glob()?

Nope, because .NET doesn’t have glob.

How can I open a file with a leading ">" or trailing blanks?

Open it normally. Perl treats these things special but in .NET IJW(it just works).

How can I reliably rename a file?

File.Move works great.

How can I lock a file?

Open the file with FileShare.None. You cannot lock a file without opening it.

Why can't I just open(FH, ">file.lock")?

Because operating systems don’t work that way.

I still don't get locking. I just want to increment the number in the file. How can I do this?

Didn’t anyone tell you that web-page hit counters were useless? (Christiansen & D'foy, 2007)

All I want to do is append a small amount of text to the end of a file. Do I still have to use locking?

You probably should. Most documentation of writing to a file doesn’t show the proper use of FileShare.Read.

How do I randomly update a binary file?

Just seek and write. Keep in mind that “write” is an overwrite and not a shift/insert write, thus if you want to insert you will need to copy the entire remaining file to offset what you have to write.

How do I get a file's timestamp in C#?

File.GetCreationTime in System.IO.

How do I set a file's timestamp in C#?

File.SetCreationTime in System.IO

How do I print to more than one file at once?

The write way would probably be to inherit from Stream and implement your own writer.

How can I read in an entire file all at once?

Use StreamReader.ReadToEnd(), File.ReadAllBytes(), File.ReadAllLines(), or File.ReadAllText()

How can I read in a file by paragraphs?

.NET stream and file readers don’t have anything like perl’s $/ (record separator). You would have to implement this yourself.

How can I read a single character from a file? From the keyboard?

From a file, StreamReader.Read() does exactly this.

From the keyboard Console.ReadKey() will do this.

How can I tell whether there's a character waiting on a filehandle?

StreamReader.Peek returns the next character without reading it or -1 if there is no next character.

How do I do a tail -f in C#?

Just keep reading blocking IO when reading from the file. See How do I change, delete, or insert a line in a file, or append to the beginning of a file? But keep reading even when ReadLine() returns null.

How do I dup() a filehandle in C#?

You can dup a stream because StreamReader has a constructor for a given stream.

Usually you won’t need a dup.

How do I close a file descriptor by number?

You don’t. Close the stream or reader/writer.

Why can't I use "C:\temp\foo" in DOS paths? Why doesn't `C:\temp\foo.exe` work?

C# strings are just like C strings. \t is a tab and \f is a form feed. You can either escape the backslashes or use the special C# @ prefixed string literal to prevent escape characters from being processed.

@”C:\temp\foo” instead of “c:\\temp\\foo”. To include a quotation mark, double quote it. @”I like to quote things “”and”” stuff”;

Why doesn't glob("*.*") get all the files?

In unix not all files have a period and a three letter extension.

Instead of glob, use System.IO.Directory.GetDirectories(@“c:\Users\jrwren”,”*.doc”) There is also an override that allows specification of a SearchOption. One SearchOption is AllDirectories which will cause GetDirectories to recurse.

To find all jpg files in jrwren’s Vista homedirectory:

string[] jpegs = System.IO.GetDirectories(@”c:\Users\jrwren”,”*.jpg”,SearchOption.AllDirectories);

Why does C# let me delete read-only files? Why does -i clobber protected files? Isn't this a bug in C#?

C# doesn’t do these things, but perl might. These do not apply to .NET or C#.

How do I select a random line from a file?

Random random = new Random();

string[] lines = File.ReadAllLines(“somefile”);

string randomline = lines[random.Next(lines)];

Is an inefficient way to do it because the entire file is read into memory.

Random random = new Random();

using (StreamReader inStream = new StreamReader("inputfile"))

{

      string line;

      int lineNumber=0;

while( ( line = inStream.ReadLine() ) != null )

{

           lineNumber++;

           if(random.Next(lineNumber+1)==0) 

                 break;

      }

}

Perlfaq says this is good and from Knuth’s The Art of Computer Programming, Volume 2, Section 3.4.2. I don’t like it because it doesn’t treat all lines with equal weight. Maybe I have not implemented an equal algorithm here.

Why do I get weird spaces when I print an array of lines?

C# and .NET do not let you do this directly. string.Join(“,”,someStringArray); works fine.

Csharpfaq6: Regular Expressions

This section is surprisingly small because the rest of the FAQ is littered with answers involving regular expressions. For example, decoding a URL and checking whether something is a number are handled with regular expressions, but those answers are found elsewhere in this document (in Csharpfaq9: "How do I decode or create those %-encodings on the web" and Csharpfaq4: "How do I determine whether a scalar is a number/whole/integer/float", to be precise).

How can I hope to use regular expressions without creating illegible and unmaintainable code?

Unfortunately only 1 of the 3 techniques mentioned in perlfaq really work in C#. So comment lots outside the regex.

Whitespace and comments inside the regex do not work because C# doesn’t like multiline strings. Different delimiters don’t help because regex’s are inputted as strings to regex methods. They aren’t built into the language like in perl, boo, and javascript.

I'm having trouble matching over more than one line. What's wrong?

Maybe you should be using Regex.Matches instead of Regex.Match? You might be using incorrect modifier(s).

How can I pull out lines between two patterns that are themselves on different lines?

Perl has some .. operator that makes this easy. It really isn’t that difficult to just implement the line based reading state yourself.

private void LinesBetweenTwoPatterns(string start, string end, string input)

{

    StringReader stringreader = new StringReader(input);

    StringWriter outStream = new StringWriter();

    string line;

    bool reading = false;

    while ((line = stringreader.ReadLine()) != null)

    {

        if (Regex.IsMatch(line, start))

        {

            reading = true;

            continue;

        }

        if (Regex.IsMatch(line, end))

        {

            reading = false;

            continue;

        }

        if (reading)

            outStream.WriteLine(line);

 

    }

    Console.WriteLine(outStream.ToString());

}

LinesBetweenTwoPatterns("START", "END", PerlFaq6Resources.LinesBetweenTwoPatternsString);

 

If you want to read nested START through END patterns things get tricky and you run into the same problem described in How do I find matching/nesting anything?

I put a regular expression into $/ but it didn't work. What's wrong?

.NET stream and file readers don’t have anything like perl’s $/ (record separator). You would have to implement this yourself.

How do I substitute case insensitively on the LHS while preserving case on the RHS?

Perlfaq shows how you can substitute TEsT and get SUcCESS as a result. Why in gods name do you want to do that?

[TODO: figure out how to do this in .NET]

How can I make \w match national character sets?

It just does. You can disable this behavior by using RegexOptions.CultureInvariant.

How can I match a locale-smart version of /[a-zA-Z]/?

Use \w

How can I quote a variable to use in a regex?

Perl has a \Q which starts quote and reuses the \E which ends a number of regex modifiers. This is useful in perl if you want to match a string literal say “1*”. The * in regex would be interpreted as a modifier, but by surrounding with \Q and \E, it turns off all modifiers and treats it literal. I know of no way to do this in .NET. You will have to escape your strings manually.

What is /o really for?

It’s a perl thing, but it is important to know about compiled regular expressions. They can greatly help performance under certain conditions. Often it is as easy as passing RegexOptions.Compiled to the Regex constructor or static methods. There are pros and cons to this. While compiling the regex will yield faster execution time, it also takes time to compile and so will increase startup time.

How do I use a regular expression to strip C style comments from a file?

Sounds easy doesn’t it? But what if you have a C style comment in a string? 

string blah = “things and /* oh no don’t steal my stuff!*/ ”;

So something this simple won’t work:

string text = Regex.Replace(inputfilestring, “/\*.*?\*/”, “”);

 

Thanks again to the perlfaq. (This section should just be called regex faq since most of the concepts apply to any environment in which you can use regular expressions.)

string text = Regex.Replace(inputfilestring,

“/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)”, “$2”, RegexOptions.Singleline);

 

Thanks again to Fred Curtis who expanded this out and documented it using RegexOptions.IgnorePatternWhitespace (/x in perl).

/\*         ##  Start of /* ... */ comment

[^*]*\*+    ##  Non-* followed by 1-or-more *'s

(

 [^/*][^*]*\*+

)*          ##  0-or-more things which don't start with /

           ##    but do end with '*'

/           ##  End of /* ... */ comment

 

|         ##     OR  various things which aren't comments:

 

(

 "           ##  Start of " ... " string

 (

   \\.           ##  Escaped char

 |               ##    OR

   [^"\\]        ##  Non "\

 )*

 "           ##  End of " ... " string

 

|         ##     OR

 

 '           ##  Start of ' ... ' string

 (

   \\.           ##  Escaped char

 |               ##    OR

   [^'\\]        ##  Non '\

 )*

 '           ##  End of ' ... ' string

 

|         ##     OR

 

 .           ##  Anything other char

 [^/"'\\]*   ##  Chars which doesn't start a comment, string or escape

)

 

Can I use regular expressions to match balanced text?

Not usually, but actually there is some under the hood stack magic that .NET regex can do for you.

This example from the Grouping Constructs .NET Framework Developer’s Guide in MSDN shows how to match balanced <> characters.

// This code example demonstrates using the balancing group definition feature of

// regular expressions to match balanced left angle bracket (<) and right angle

// bracket (>) characters in a string.

 

using System;

using System.Text.RegularExpressions;

 

class Sample

{

    public static void Main()

    {

/*

    The following expression matches all balanced left and right angle brackets(<>).

    The expression:

    1)   Matches and discards zero or more non-angle bracket characters.

    2)   Matches zero or more of:

    2a)  One or more of:

    2a1) A group named "Open" that matches a left angle bracket, followed by zero

         or more non-angle bracket characters.

         "Open" essentially counts the number of left angle brackets.

    2b) One or more of:

    2b1) A balancing group named "Close" that matches a right angle bracket,

         followed by zero or more non-angle bracket characters.

         "Close" essentially counts the number of right angle brackets.

    3)   If the "Open" group contains an unaccounted for left angle bracket, the

        entire regular expression fails.

*/

    string pattern = "^[^<>]*" +

                     "(" +

                       "((?'Open'<)[^<>]*)+" +

                       "((?'Close-Open'>)[^<>]*)+" +

                     ")*" +

                     "(?(Open)(?!))$";

    string input = "<abc><mno<xyz>>";

//

    Match m = Regex.Match(input, pattern);

    if (m.Success == true)

        Console.WriteLine("Input: \"{0}\" \nMatch: \"{1}\"", input, m);

    else

        Console.WriteLine("Match failed.");

    }

}

 

/*

This code example produces the following results:

Input: "<abc><mno<xyz>>"

Match: "<abc><mno<xyz>>"

*/

Interestingly this has some mathematical implications. By implementing a stack underneath this is technically not just a regular expression. This is something that a true regular expression could not do. Regular expressions are representations of regular languages. See How do I find matching/nesting anything?

What does it mean that regexes are greedy? How can I get around it?

Most people mean that greedy regexes match as much as they can. Technically speaking, it’s actually the quantifiers (?, *, +, {}) that are greedy rather than the whole pattern. (Christiansen & D'foy, 2007)

C#, like Perl, prefers local greed and immediate gratification to overall greed. You can use the ? modifier on a quantifier to get a non-greedy version.

string s1 = “I am very very cold”;

string withoutVery = Regex.Replace(s1,”ve.*y”,””); // “I am cold”

string withoutOneVery = Regex.Replace(s1,”ve.*?y”,””); // “I am very cold”

 

How do I process each word on each line?

Use the split function.

StringReader inStream = new StringReader(someinputstring);

string line;

while ( (line = inStream.ReadLine())!=null)

{

    foreach (string word in line.Split(' '))

    {

      //do something with word here.

        Console.WriteLine(word+word.Length);

    }

}

You could use Regex.Split(line,”somethinghere”) instead of string.Split to split on other word separators or “(\w+)” to ignore multiple spaces between words.

How can I print out a word-frequency or line-frequency summary?

For words it is VERY similar to the previous question. The answer is “use a hash”.

StringReader inStream = new StringReader(someinputstring);

string line;

Dictionary<string,int> wordCount = new Dictionary<string,int>();

Dictionary<string,int> lineCount = new Dictionary<string,int>();

while ((line = inStream.ReadLine()) != null)

{

    foreach (string word in line.Split(' '))

    {

        if (wordCount.ContainsKey(word))

            wordCount[word]++;

        else

            wordCount[word] = 1;

    }

    if (lineCount.ContainsKey(line))

        lineCount[line]++;

    else

        lineCount[line] = 1;

}

How can I do approximate matching?

I like to Compute Levenshtein distance.

/// <summary>

/// Compute Levenshtein distance.

/// from http://www.merriampark.com/ldcsharp.htm

/// </summary>

public

#if NET_2_0

static

#endif

class Distance

{

        /// <summary>

        /// Compute Levenshtein distance

        /// </summary>

        /// <param name="s">String 1</param>

        /// <param name="t">String 2</param>

        /// <returns>Distance between the two strings.

        /// The larger the number, the bigger the difference.

        /// </returns>

        public static int LD (string s, string t)

        {

                int n = s.Length; //length of s

                int m = t.Length; //length of t

                int[,] d = new int[n + 1, m + 1]; // matrix

                int cost; // cost

                // Step 1

                if(n == 0) return m;

                if(m == 0) return n;

                // Step 2

                for(int i = 0; i <= n; d[i, 0] = i++);

                for(int j = 0; j <= m; d[0, j] = j++);

                // Step 3

                for(int i = 1; i <= n;i++)

                {

                        //Step 4

                        for(int j = 1; j <= m;j++)

                        {

                                // Step 5

                                cost = (t.Substring(j - 1, 1) == s.Subst

ring(i - 1, 1) ? 0 : 1);

                                // Step 6

                                d[i, j] = System.Math.Min(System.Math.Mi

n(d[i - 1, j] + 1, d[i, j - 1] + 1),

                                        d[i - 1, j - 1] + cost);

                        }

                }

 

                // Step 7

                return d[n, m];

        }

}

[TODO: find some other string approximation matching libraries]

How do I efficiently match many regular expressions at once?

Compile your regular expressions. See What is /o really for?

You may be able to combine multiple regular expressions into a single regex. Instead of match “foo” and then match “bar” and then match “baz”. Try “(foo|bar|baz)”.

For more details on regular expression efficiency, see Mastering Regular Expressions by Jeffrey Freidl. He explains how regular expressions engine work and why some patterns are surprisingly inefficient. Once you understand how perl applies regular expressions, you can tune them for individual situations. (Christiansen & D'foy, 2007)

Why don't word-boundary searches with \b work for me?

Ensure that you know what \b really does: it's the boundary between a word character, \w, and something that isn't a word character. That thing that isn't a word character might be \W, but it can also be the start or end of the string.

It's not (not!) the boundary between whitespace and non-whitespace, and it's not the stuff between words we use to create sentences.

In regex speak, a word boundary (\b) is a "zero width assertion", meaning that it doesn't represent a character in the string, but a condition at a certain position. (Christiansen & D'foy, 2007)

Why does using $&, $`, or $' slow my program down?

.NET and C# doesn’t have these concepts (thank God). They are not recommended for use in perl.

What good is \G in a regular expression?

You use the \G anchor to start the next match on the same string where the last match left off. The regular expression engine cannot skip over any characters to find the next match with this anchor, so \G is similar to the beginning of string anchor, ^. The \G anchor is typically used with the g flag. It uses the value of pos() as the position to start the next match. As the match operator makes successive matches, it updates pos() with the position of the next character past the last match (or the first character of the next match, depending on how you like to look at it). Each string has its own pos() value.

Suppose you want to match all of consecutive pairs of digits in a string like "1122a44" and stop matching when you encounter non-digits. You want to match 11 and 22 but the letter <a> shows up between 22 and 44 and you want to stop at a. Simply matching pairs of digits skips over the a and still matches 44. (Christiansen & D'foy, 2007)

string blah = “1122a44”;

MatchCollection matches = Regex.Matches(blah,”(\d\d)”);

// three matches, each with one grouping value of 11, 22, 44

 

\G changes this behavior so that a clogs things up. \G forces the match to start from the last position - with the a. “a” doesn’t match \d so the match fails

string blah = “1122a44”;

MatchCollection matches = Regex.Matches(blah,”\G(\d\d)”);

// three matches, each with one grouping value of 11, 22

 

Are regexes DFAs or NFAs? Are they POSIX compliant?

[TODO: find .NET Regex docs on this]

What's wrong with using grep[ConvertAll] in a void context?

The problem is that .NET will create an Array in which to store the results. Use Array.ForEach or better yet in .NET 3.0 use LINQ or an IEnumerable<T> extension method from Queryable. These methods return IEnumerables instead of pre-built List<T> or Array. This means that the result is built on demand as you ask for it.

How can I match strings with multibyte characters?

.NET does this for you. .NET strings are fully Unicode compliant including multibyte chars. There are even some Unicode character classes available. \p{Lu} for letters which are uppercase, \p{Ll} for letters which are lowercase. See Character Classes in the MSDN Documention .NET Framework Developer's Guide. Eat your heart out perl! This appears to be something that .NET regular expressions do that perl’s do not, or at least not easily.

How do I match a regular expression that's in a variable?

It just works.

string regex = someOtherRegexPiece + “\d\d\w*\d?” + anotherRegexPiece;

for(Match match in Regex.Matches(input,regex)) {…

Csharpfaq7: General C# Language Issues

General C# language issues that don't clearly fit into any of the other sections.

Can I get a BNF/yacc/RE for the C# language?

Mono is open source, just dive into their sources and find it. Microsoft also has an open source implementation known as Rotor which may be insightful.

What are all these $@%&* punctuation signs, and how do I know when to use them?

This is FAR more applicable in perl, but C# has its punctuation signs too!

The Question Mark: bool? Is a C# shorthand way of saying Nullable<bool>. The ? can be appended to any value type to ask for a nullable of that value type.

The At@ sign: is used to escape strings in C#. No escape characters will be interpreted and you can span multiple lines.

string literal = @”This string will actually print backslash n here: \n and

the newline will be literal in the this multiline string”;

 

The At@ sign can also be used to escape a keyword

private int ReturnKeyword()

{

    int @return = 0;

    return @return;

}

 

Do I always/never have to quote my strings or use semicolons and commas?

You always have to. This isn’t perl!

How do I skip some return values?

I am not sure what this means in a C# context, but I can show some C# code that matches one of the perl examples here (the other two cannot be done in C# - and for good reason).

return GetSomeThingThatReturnsSomethingIndexable()[2];

Event this is probably not a good idea unless you are certain that this method will always return something with an integer index of two.

How do I temporarily block warnings?

You can use #pragma directives. My favorite is to turn on warnings as errors and override the warnings with #pragma directives. Two I find very useful are 1591 and 3008.

// We don't need XML docs in this file!

#pragma warning  disable 1591

// This generated file may not be CLS compliant, OH WELL!

#pragma warning  disable 3008

#pragma warning restore 1591

#pragma warning restore 3008

 

What's an extension[P/Invoke]?

P/Invoke is a way of calling native code (always C?) from Perl.  http://www.pinvoke.net is a great resource.

Why do C# operators have different precedence than C operators?

Because this is easier.

[TODO: detail the differences if any]

How do I declare/create a structure?

Exactly as you would a class, but use the struct keyword. The difference is that a “struct” is a value type instead of a reference type. There is a lot implied in this difference.

How do I create a module?

Use CSC /target:module, but you probably really want /target:library. The former will compile to a .netmodule file. The compiler will not generate an assembly manifest. This can be useful if you wish to compile some vb.net files and some C# files and then compile them into the same assembly. You can add a netmodule to an assembly when you build the assembly by using /addmodule. There is an excellent tool called ILMerge which lets you merge two assemblies by extracting their modules and creating a new assembly from the extracted modules.

How do I create a class?

This is pretty fundamental to C#. (It isn’t fundamental to perl.)  You should already know this, but here is an example with a field, a property, two events, a delegate and the second class as EventArgs:

 

public class MyClass

{

    private string _FieldOne;

    private string _PropertyOne;

    public string PropertyOne

    {

        get { return _PropertyOne; }

        set

        {

            _PropertyOne = value;

        }

    }

    public delegate void MyEventHandler(object sender, EventArgs ea);

    public event MyEventHandler MyEvent;

    public event EventHandler<MyEventArgs> MyOtherEvent;

    public MyClass()

    {

        if (MyEvent!=null)

            MyEvent(this, new EventArgs());

        if (MyOtherEvent!=null)

            MyOtherEvent(this, new MyEventArgs("hi"));

    }

}

public class MyEventArgs : EventArgs

{

   

    public MyEventArgs(string message)

    {

        this._Message = message;

    }

    private string _Message;

    public string Message

    {

        get { return _Message; }

        set

        {

            _Message = value;

        }

    }

}

How can I tell if a variable is tainted?

HUH? We don’t play with our taint in C#.

What's a closure?

There has been TONS written on this. Rather than duplicate it all, I recommend you start with the Wikipedia page and read it completely. It gives a good introduction. Then google for C# closures and read the many blog posts.

The short answer is that it is a function paired with environment. C# anonymous methods enable closures to be built easily. LINQ uses this, among other things, extensively.

[TODO: show a simple closure example]

What is variable suicide and how can I prevent it?

C# and .NET are not perl.

How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?

You just do. Functions aka Methods are passed by means of a delegate. FileHandles, Arrays, Hashes, Methods, Regex, Functions and delegates are all objects.

How do I create a static variable?

Use the static keyword where the variable is defined.

public class MyClass

{

    private static string _FieldOne;

 

What's the difference between dynamic and lexical (static) scoping? Between local() and my()?

Thank god that perl is not C#.

How can I access a dynamic variable while a similarly named lexical is in scope?

The concept is not the same as the mess that is perl’s variable scoping, but knowing to use this is important. See the use of this in the class example at How do I create a class?

What's the difference between deep and shallow binding?

I can’t think of any parallels to C# or .NET here.

Why doesn't "my($foo) = <FILE>;" work right?

C# doesn’t have a <> readline operator. .NET has some “read all lines into an array of strings” methods mentioned in section 5 of csharpfaq, but the issues with perl do not apply. All is good here in C# land.

How do I redefine a builtin function, operator, or method?

If the class is sealed, you are kinda screwed. Use a bridge or adapter pattern. If the class is not sealed, you can inherit and use a strategy pattern. You can overload operators in C#. You can declare both explicit and implicit type conversions. You can even cause overloaded operators to return some other type. For example causing == to return a non-bool type seems stupid, but in certain cases (see NHibernate Query Generator) it makes for very readable code.

What's the difference between calling a function as &foo and foo()?

C# doesn’t have or need this.

How do I create a switch or case statement?

You just do.

switch (val)

{

    case 0:

        DoStuff();

        break;

    case 1:

        break;

}

//you can even switch on strings (unlike C)

switch (someString)

{

    case "can't":

        Stuff();

        break;

    case "do this in C":

        break;

}

How can I catch accesses to undefined variables, functions, or methods?

The compiler will do this. This is not ruby. We do not have method_missing.

More common are undefined Dictionary keys. These result in a runtime error. Strings literals are Evil. The guys over at Eleutian hate string literals. http://blog.eleutian.com/PermaLink,guid,088e158b-cd3c-4920-8df5-a3628013cc1d.aspx

Why can't a method included in this same file be found?

You misspelled the name, or it is out of scope. C# has no file level scope like C or Perl. You must make the method accessible and access the method appropriately, through an instance if needed.

How can I find out my current package[assembly]?

Assembly.GetAssembly(MyType.GetType()) where MyType is the type of your current class.

How can I comment out a large block of C# code?

/* blah blah */

Many editors such as Visual Studio, SharpDevelop and MonoDevelop have shortcuts to just highlight code and click a button to have it commented.

You can also “comment” out C# code by using #if 0… #endif

How do I clear a package[assembly]?

You don’t. You cannot unload assemblies either. But you can unload an AppDomain. An AppDomain in .NET is like a .NET Process within the operating system process. You can have multiple AppDomains within the same process. Many plugin or add-in systems work this way by loading the add-ins in a separate AppDomain. When you call methods between AppDomains you are effectively doing remoting so objects just be Serializable or inherit from MarshalByRefObject. .NET 3.5 is to include an add-in system. Mono has Mono.AddIns. You should probably use these pre-existing add-in libraries if you want to build an add-in system in your application.

How can I use a variable as a variable name?

You can do this using Reflection.

[TODO: example]

What does "bad interpreter" mean?

I have no idea. C# doesn’t interpret.

Csharpfaq8: System Interaction

This section of the C# FAQ covers questions involving operating system interaction. Topics include interprocess communication (IPC), control over the user-interface (keyboard, screen and pointing devices), and most anything else not related to data manipulation.

How do I find out which operating system I'm running under?

 

How come exec() doesn't return?

How do I do fancy stuff with the keyboard/screen/mouse?

How do I print something out in color?

How do I read just one key without waiting for a return key?

How do I check whether input is ready on the keyboard?

How do I clear the screen?

How do I get the screen size?

How do I ask the user for a password?

How do I read and write the serial port?

How do I decode encrypted password files?

How do I start a process in the background?

How do I trap control characters/signals?

How do I modify the shadow password file on a Unix system?

How do I set the time and date?

How can I sleep() or alarm() for under a second?

How can I measure time under a second?

How can I do an atexit() or setjmp()/longjmp()? (Exception handling)

Why doesn't my sockets program work under System V (Solaris)? What does the error message "Protocol not supported" mean?

How can I call my system's unique C functions from C#?

Where do I get the include files to do ioctl() or syscall()?

Why do setuid C# scripts complain about kernel problems?

How can I open a pipe both to and from a command?

Why can't I get the output of a command with system()?

How can I capture STDERR from an external command?

Why doesn't open() return an error when a pipe open fails?

What's wrong with using backticks in a void context?

How can I call backticks without shell processing?

Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?

How can I convert my shell script to C#?

Can I use C#to run a telnet or ftp session?

How can I write expect in C#?

Is there a way to hide C#'s command line from programs such as "ps"?

I {changed directory, modified my environment} in a C# script. How come the change disappeared when I exited the script? How do I get my changes to be visible?

How do I close a process's filehandle without waiting for it to complete?

How do I fork a daemon process?

How do I find out if I'm running interactively or not?

How do I timeout a slow event?

How do I set CPU limits?

How do I avoid zombies on a Unix system?

How do I use an SQL database?

How do I make a system() exit on control-C?

How do I open a file without blocking?

How do I tell the difference between errors from the shell and C#?

How do I install a module from CPAN?

What's the difference between require and use?

How do I keep my own module/library directory?

How do I add the directory my program lives in to the module/library search path?

How do I add a directory to my include path (@INC) at runtime?

What is socket.ph and where do I get it?

Csharpfaq9: Networking

Networking, the internet, and a few on the web.

What is the correct form of response from a CGI script?

My CGI script runs from the command line but not the browser. (500 Server Error)

How can I get better error messages from a CGI program?

How do I remove HTML from a string?

How do I extract URLs?

How do I download a file from the user's machine? How do I open a file on another machine?

How do I make an HTML pop-up menu with C#?

How do I fetch an HTML file?

How do I automate an HTML form submission?

How do I decode or create those %-encodings on the web?

How do I redirect to another page?

How do I put a password on my web pages?

How do I edit my .htpasswd and .htgroup files with C#?

How do I make sure users can't enter values into a form that cause my CGI script to do bad things?

How do I parse a mail header?

How do I decode a CGI form?

How do I check a valid mail address?

How do I decode a MIME/BASE64 string?

How do I return the user's mail address?

How do I send mail?

How do I use MIME to make an attachment to a mail message?

How do I read mail?

How do I find out my hostname, domainname, or IP address?

How do I fetch a news article or the active newsgroups?

How do I fetch/put an FTP file?

How can I do RPC in C#?

 

Works Cited

Christiansen, T., & D'foy, B. (2007, July 9). perlfaq. Retrieved from http://faq.perl.org/