Csharpfaq
How to contribute to the Csharpfaq?
What will happen if you mail your C# programming
problems to the authors?
Csharpfaq1: General Questions about C#
Who supports C#? Who develops it? Why is it free?
Which version of C# should I use?
How does C# compare with other languages like Java,
Python, C, C++, REXX, Scheme or Tcl?
When shouldn’t I program in C#?
What’s the difference between C# and c-sharp?
Is it a C# program or a C# script?
How can I convince others to use C#?
Csharpfaq2: Obtaining and Learning about C#
What machines support C#? Where do I get it?
How can I get a binary version of C#?
I don’t have a C compiler. How can I build my own C#
compiler?
I copied the C# compiler binary from one machine to
another, but it doesn’t work.
What modules and extensions are available for C#?
Is there an ISO or ANSI certified version of C#?
Where can I get information on C#?
What are the C# newsgroups on Usenet? Where do I post
questions?
Where should I post source code?
Which magazines have C# content?
What mailing lists are there for C#?
Where are the archives for mono and mono-devel?
Where can I buy a commercial version of C#?
What is csharp.com, csharp-station.com,
csharphelp.com, codeproject.com, etc?
How can I use C# interactively?
How do I find which modules/libraries are installed on
my system?
How do I debug my C# programs?
How do I profile my C# programs?
How do I cross-reference my C# programs?
Is there a pretty-printer (formatter) for C#?
Is there an IDE or Windows C# editor?
Where can I get C# macros for vi?
Where can I get csharp-mode for emacs?
How can I use X or Tk with C#?
How can I make my C# program run faster?
How can I make my C# program take less memory?
Is it safe to return a reference to a local or lexical
data?
How can I free an array or hash so my program shrinks?
How can I make my CGI script more efficient?
How can I hide the source for my C# program?
How can I compile my C# program into byte code or C?
How can I get #!/usr/bin/csharp to work on [MS-DOS,
NT, … ] ?
Can I write useful C# programs on the command line?
Why don’t C# one-liners work on my DOS/Mac/VMS system?
Where can I learn about CGI or Web programming in C#?
Where can I learn about object-oriented C#
programming?
Where can I learn about linking C with C#?
I’ve read XYZ but I can’t embed C# in my C program;
what am I doing wrong?
When I tried to run my script, I got this message.
What does it mean?
What’s MakeMaker? [x:What is MSBUILD or Nant?]
Why isn’t my octal data interpreted correctly?
Does C# have a round() function? What about ciel() and
floor()? Trig functions?
How do I convert between numeric
representations/bases/radixes?.
Why doesn’t & work the way I want it to?
How do I perform an operation on a series of integers?
How can I output Roman numerals?
Why aren’t my random numbers random?
How do I get a random number between X and Y?
How do I find the day or week of the year?
How do I find the current century or millennium?
How can I compare two dates and find the difference?
How can I take a string and turn it into epoch
seconds?
How can I find the Julian Day?
How do I find yesterday’s date?
Does C# have a Year 2000 problem? Is C# Y2K compliant?
How do I remove consecutive pairs of characters?
How do I expand function calls in a string?
How do I find matching/nesting anything?
How do I expand tabs in a string?
How do I reformat a paragraph?
How can I access or change N characters of a string?
How do I change the Nth occurrence of something?
How can I count the number of occurrences of a
substring within a string?
How do I capitalize all the words on one line?
How can I split a [character] delimited string except
when inside [character]?
How do I strip blank space from the beginning/end of a
string?
How do I pad a string with blanks or pad a number with
zeroes?
How do I extract selected columns from a string?
How do I find the soundex value of a string?
How can I expand variables in text strings?
What's wrong with always quoting "$vars"?
Why don't my <<HERE documents work?
What is the difference between a list and an array?
What is the difference between $array[1] and
@array[1]?
How can I remove duplicate elements from a list or
array?
How can I tell whether a certain element is contained
in a list or array?
How do I compute the difference of two arrays? How do
I compute the intersection of two arrays?
How do I test whether two arrays or hashes are equal?
How do I find the first array element for which a
condition is true?
How do I handle circular lists?
How do I shuffle an array randomly?
How do I process/modify each element of an array?
How do I select a random element from an array?
How do I permute N elements of a list?
How do I sort an array by (anything)?
How do I manipulate arrays of bits?
Why does defined() return true on empty arrays and
hashes?
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?
How do I handle binary data correctly?
How do I determine whether a scalar is a
number/whole/integer/float?
How do I keep persistent data across program calls?
How do I print out or copy a recursive data structure?
How do I define methods for every class/object?
How do I verify a credit card checksum?
How do I pack arrays of doubles or floats for XS code?
How do I flush/unbuffer an output filehandle? Why must
I do this?
How do I change, delete, or insert a line in a file,
or append to the beginning of a file?
How do I count the number of lines in a file?
How can I use Perl's -i option from within a C#
program?
How do I make a temporary file name?
How can I manipulate fixed-record-length files?
How can I use a filehandle indirectly?
How can I set up a footer format to be used with
write()?
How can I write() into a string?
How can I output my numbers with commas added?
How can I translate tildes (~) in a filename?
How come when I open a file read-write it wipes it
out?
Why do I sometimes get an "Argument list too
long" when I use <*>?
Is there a leak/bug in glob()?
How can I open a file with a leading ">"
or trailing blanks?
How can I reliably rename a file?
Why can't I just open(FH, ">file.lock")?
I still don't get locking. I just want to increment
the number in the file. How can I do this?
How do I randomly update a binary file?
How do I get a file's timestamp in C#?
How do I set a file's timestamp in C#?
How do I print to more than one file at once?
How can I read in an entire file all at once?
How can I read in a file by paragraphs?
How can I read a single character from a file? From
the keyboard?
How can I tell whether there's a character waiting on
a filehandle?
How do I dup() a filehandle in C#?
How do I close a file descriptor by number?
Why can't I use "C:\temp\foo" in DOS paths?
Why doesn't `C:\temp\foo.exe` work?
Why doesn't glob("*.*") get all the files?
How do I select a random line from a file?
Why do I get weird spaces when I print an array of
lines?
Csharpfaq6: Regular Expressions
How can I hope to use regular expressions without
creating illegible and unmaintainable code?
I'm having trouble matching over more than one line.
What's wrong?
How can I pull out lines between two patterns that are
themselves on different lines?.
I put a regular expression into $/ but it didn't work.
What's wrong?
How do I substitute case insensitively on the LHS
while preserving case on the RHS?
How can I make \w match national character sets?
How can I match a locale-smart version of /[a-zA-Z]/?
How can I quote a variable to use in a regex?
How do I use a regular expression to strip C style
comments from a file?
Can I use regular expressions to match balanced text?
What does it mean that regexes are greedy? How can I
get around it?
How do I process each word on each line?
How can I print out a word-frequency or line-frequency
summary?
How can I do approximate matching?
How do I efficiently match many regular expressions at
once?
Why don't word-boundary searches with \b work for me?
Why does using $&, $`, or $' slow my program down?
What good is \G in a regular expression?
Are regexes DFAs or NFAs? Are they POSIX compliant?
What's wrong with using grep in a void context?
How can I match strings with multibyte characters?
How do I match a regular expression that's in a variable?
Csharpfaq7: General C# Language Issues
Can I get a BNF/yacc/RE for the C# language?
What are all these $@%&* punctuation signs, and
how do I know when to use them?.
Do I always/never have to quote my strings or use
semicolons and commas?
How do I skip some return values?
How do I temporarily block warnings?
Why do C# operators have different precedence than C
operators?
How do I declare/create a structure?
How can I tell if a variable is tainted?
What is variable suicide and how can I prevent it?
How can I pass/return a {Function, FileHandle, Array,
Hash, Method, Regex}?
How do I create a static variable?
What's the difference between dynamic and lexical (static)
scoping? Between local() and my()?
How can I access a dynamic variable while a similarly
named lexical is in scope?
What's the difference between deep and shallow
binding?
Why doesn't "my($foo) = <FILE>;" work
right?
How do I redefine a builtin function, operator, or
method?
What's the difference between calling a function as
&foo and foo()?
How do I create a switch or case statement?
How can I catch accesses to undefined variables,
functions, or methods?
Why can't a method included in this same file be
found?
How can I find out my current package?
How can I comment out a large block of C# code?
How can I use a variable as a variable name?
What does "bad interpreter" mean?
Csharpfaq8: System Interaction
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 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)
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?
Is there a way to hide C#'s command line from programs
such as "ps"?
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 avoid zombies on a Unix system?
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?
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 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 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 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 use MIME to make an attachment to a mail
message?
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?
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.
http://workwith.net/faq/csharp/
You can mail corrections, additions, and suggestions to <csharpfaq-workers@lists.xmtp.net>.
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.
Very general, high-level questions about 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.
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.
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.
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.
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.
“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.“
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.
“Favorable in some areas, unfavorably in
others.”
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#.
Yes.
“When your manager forbids it – but consider replacing them J.”
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#.
I am not sure. Probably copyright. They are pronounced the same. C# is “see sharp” not “see pound” or “see number”.
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
“JAPH stands for ‘Just another Perl hacker’”
“Appeal to their self interest!”
Where to find source and documentation for C#, support and related matters.
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
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?”
“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.”
“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…”
I’ll assume you are referring to Mono in which case you should read their INSTALL file and their documentation.
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.
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.
There are many great books, websites, magazine articles as well as MSDN reference documentation articles.
There aren’t any. In the mono world, try the mono developer email lists. These can be accessed via NNTP by using Gmane.
“You should post source code to whichever group is most
appropriate…”
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.
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.
TODO: fill this in with recommendations.
TODO: fill this in with recommendations.
http://www.mono-project.com/Mailing_Lists
See Gmane.
Microsoft provides a commercial version of C#. You may also negotiate support for Mono and Mono’s C# through Novel.
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
TODO: put a list of good website resources here.
Programmer tools and programming support.
“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?”
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.
There have been a couple of attempts at C# interpreters but none was a full C# implementation AFAIK
Not that I know of. PowerShell is very different from C# and is a .NET Language of its own.
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.
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.
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.
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/
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
Yes, Exuberant ctags (http://ctags.sourceforge.net) has support for C#.
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.
Gvim ships with “cs” syntax highlighting, indent, and and file type support.
http://www.emacswiki.org/cgi-bin/wiki/CSharpMode
http://www.mono-project.com/MonoCurses
http://www.mono-project.com/Gtk
I know of no wait to use the antiquated “tk” with C# or Mono.
http://www.mono-project.com/Performance_Tips
While this is mono documentation, nearly all of the concepts hold true for the MS runtime.
http://www.mono-project.com/Performance_Tips
While this is mono documentation, nearly all of the concepts hold true for the MS runtime.
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.”
“You usually can't.”
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.
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
“Delete it. :-) Seriously, there are a number of (mostly
unsatisfactory) solutions with varying levels of "security".”
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.
“In general, you can't do this.”
Runtime executed code is already byte code compiled.
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”.
Not really. Certainly not like you can write one liners in perl.
See the previous question.
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
See books, magazines, mailing lists, tutorials and websites.
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’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
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.
C# programs are usually distributed with either a Makefile, or a MSBUILD csproj or sln file, or a nant build script.
Manipulating numbers, dates, strings, arrays, hashes, and miscellaneous data issues.
Everything I learned about perl I learned from perlfaq4 – JRW
“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.”
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)?".
The C# language standard does not support octal characters constants by default.
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().
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.
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.
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.
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.
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/
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:
Computers are good at being predictable and bad at being
random (despite appearances caused by bugs in your programs :-).
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.
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);
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);
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);
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 );
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
http://www.codeproject.com/csharp/JalaliCalendar.asp
http://heybo.com/weblog/posts/254.aspx
Calculate the Julian Date
(DateTime.UtcNow – DateTime.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);
DateTime.Now.AddDays(1)
.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.
There are many ways. CastleProject has a Validation system which works well with MonoRail. EnterpriseLibrary from Microsoft had a Validation system.
It depends on what you mean. URL and Html escapes can be handled with HttpUtility class in System.Web namespace and assembly.
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.
/* 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.
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.
This isn't something that can be done in one regular
expression, no matter how complicated.
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.
Array.Reverse will reverse an array in place.
string mystring = “hello”;
char[] mystringCharArr = mystring.ToCharArray()
Array.Reverse(mystringCharArr)
string reverse = new string ( mystringCharArr );
string tabSpaces = new string(“ “,4);
string expanded = (new Regex(@”\t”)).Replace(mystring, tabSpaces);
[TODO: find a Text::Wrap and Text::Autoformat .NET Library or C# code]
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
You have to keep track of N yourself.
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] );
}
}
int count = 0;
while( -1 != mystring.Count(“x in mystring”) )
count ++;
string.Count has overrides for Char and string and other overrides.
.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”);
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\"".
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))
{