Is there a heredoc notation for strings in C#, preferably one where I don't have to escape anything (including double quotes, which are a quirk in verbatim strings)?
As others have said, there isn't.
Personally I would avoid creating them in the first place though - I would use an embedded resource instead. They're pretty easy to work with, and if you have a utility method to load a named embedded resource from the calling assembly as a string (probably assuming UTF-8 encoding) it means that:
If your embedded document is something like SQL, XSLT, HTML etc you'll get syntax highlighting because it really will be a SQL (etc) file
You don't need to worry about any escaping
You don't need to worry about either indenting your document or making your C# code look ugly
You can use the file in a "normal" way if that's relevant (e.g. view it as an HTML page)
Your data is separated from your code
Well even though it doesn't support HEREDOC's, you can still do stuff like the following using Verbatim strings:
string miniTemplate = #"
Hello ""{0}"",
Your friend {1} sent you this message:
{2}
That's all!";
string populatedTemplate = String.Format(miniTemplate, "Fred", "Jack", "HelloWorld!");
System.Console.WriteLine(populatedTemplate);
Snagged from:
http://blog.luckyus.net/2009/02/03/heredoc-in-c-sharp/
No, there is no "HEREDOC" style string literal in C#.
C# has only two types of string literals:
Regular literal, with many escape sequences necessary
Verbatim literal, #-quoted: doublequotes need to be escaped by doubling
References
csharpindepth.com - General Articles - Strings
MSDN - C# Programmer's Reference - Strings
String literals are of type string and can be written in two forms, quoted and #-quoted.
November 2022 update:
Starting with C# 11 this is now possible using Raw string literals:
var longMessage = """
This is a long message.
Some "quoted text" here.
""";
Related
I'm refactoring some code and one task is to place hard-coded strings into resources. I have this string in code:
var s = $"Last Updated: {DateTime.Now}";
So now how can I extract this string into a resource. Currently I think only this is possible:
var s = string.Format(MyStrings.LastUpdated, DateTime.Now);
where, MyStrings.LastUpdated would be:
Last Updated: {0}
Is this the only way or is there a newer way available?
The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolation expressions. When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations of the expression results.
As stated in the language reference for string interpolation with $, the operator identifies a string literal, so you cannot use a resource or variable for the format string itself.
Extracting the format string and formatting it using string.Format is a reasonable way to do this. Nevertheless, you should keep in mind that these format strings might contain complex expressions involving names or numbers and other format specifiers. So you should carefully communicate that your translator does not change or remove them, otherwise your application might show unexpected behavior. On the one hand, this might be inconvenient, but on the other hand you can only protect the expressions in your format string from modification if you separate them from your localizable resources and concatenate them yourself, which is infeasible.
Let's say I want to assign a text (which contains many double quotes) into variable. However, the only way seems to manually escape:
string t = "Lorem \"Ipsum\" dummy......
//or//
string t = #"Lorem ""Ipsum"" dummy.....
Is there any way to avoid manual escaping, and instead use something universal (which I dont know in C#) keywoard/method to do that automatically? In PHP, it's untoldly simple, by just using single quote:
$t = 'Lorem "Ipsum" dummy .......
btw, please don't bomb me with critiques "Why do you need to use that" or etc. I need answer to the question what I ask.
I know this answer may not be satisfying, but C# sytnax simply won't allow you to do such thing (at the time of writing this answer).
I think the best solution is to use resources. Adding/removing and using strings from resources is super easy:
internal class Program
{
private static void Main(string[] args)
{
string myStringVariable = Strings.MyString;
Console.WriteLine(myStringVariable);
}
}
The Strings is the name of the resources file without the extension (resx):
MyString is the name of your string in the resources file:
I may be wrong, but I conjecture this is the simplest solution.
No. In C# syntax, the only way to define string literals is the use of the double quote " with optional modifiers # and/or $ in front. The single quote is the character literal delimiter, and cannot be used in the way PHP would allow - in any version, including the current 8.0.
Note that the PHP approach suffers from the need to escape ' as well, which is, especially in the English language, frequently used as the apostrophe.
To back that up, the EBNF of the string literal in current C# is still this:
regular_string_literal '"' { regular_string_literal_character } '"'
The only change in the compiler in version 8.0 was that now, the order of the prefix modifiers $ (interpolated) and # (verbatim) can be either #$ or $#; it used to matter annoyingly in earlier versions.
Alternatives:
Save it to a file and use File.ReadAllText for the assignment, or embed it as a managed ressource, then the compiler will provide a variable in the namespace of your choice with the verbatim text as its runtime value.
Or use single quotes (or any other special character of your choice), and go
var t = #"Text with 'many quotes' inside".Replace("'", #"""");
where the Replace part could be modeled as an extension to the String class for brevity.
The following folder path stored on a database table as \\SnowAngel\IcedData. However when reading from the database it is coming as:
string myFolderName = "\\\\SnowAngel\\IcedData"; Where SnowAngel is the server name.
Regex.Unescape(myFolderName);
The above line throws the following exception:
{"parsing \"\\SnowAngel\IcedData\" - Unrecognized escape sequence \I."}
What I'm missing here ?
One has to deal with two parsers, the first is the C# language and the second is the regex parser. You have added multiple slashes to speak to the C# parser and that is confusing to the regex parser.
I recommend that you use the C# literal # when dealing with regex patterns. That way one doesn't have to worry about the C# parser. Simply change it to
string myFolderName = #"\\SnowAngel\IcedData";
and work with it in regex, though that doesn't look like a pattern.
I am reading a C# source file.
When I encounter a string, I want to get it's value.
For instance, in the following example:
public class MyClass
{
public MyClass()
{
string fileName = "C:\\Temp\\A Weird\"FileName";
}
}
I would like to retrieve
C:\Temp\A Weird"FileName
Is there an existing procedure to do that?
Coding a solution with all the possible cases should be quite tricky (#, escape sequences. ...).
I am convinced such procedure exists...
I would like to have the dual function too (to inject a string into a C# source file)
Thanks in advance.
Philippe
P.S:
I gave an example with a filename, but I look for a solution working for all kinds of strings.
I'm pretty sure you can use CodeDOM to read a C# code file and parse its elements. It generates a code tree, and then you can look for nodes representing strings.
http://www.codeproject.com/Articles/2502/C-CodeDOM-parser
Other CodeDom parsers:
http://www.codeproject.com/Articles/14383/An-Expression-Parser-for-CodeDom
NRefactory: https://github.com/icsharpcode/NRefactory and http://www.codeproject.com/Articles/408663/Using-NRefactory-for-analyzing-Csharp-code
There is a way of extracting these strings using a regular expression:
("(\\"|[^"])*")
This particular one works on your simple example and gives the filename (complete with leading and trailing quote characters); whether it would work on more complex ones I can't easily tell unfortunately.
For clarity, (\\"|[^"]) matches any character apart from ", except where it has a leading \ character.
Just use ".*" Regex to match all string values, then remove trailing inverted commas and unescape it.
this will allow \" and "" characters inside your string
so both "C:\\Temp\\A Weird\"FileName" and "Hello ""World""" will match
As we all know,we can use
string aa=#"E:\dev_workspace1\AccessCore\WebRoot\DataFile"
in c# in order not to double the '\'.
But how to do in java?
Unfortunately, there is no full-string escape operator in Java. You need to write the code as:
String aa = "E:\\dev_workspace1\\AccessCore\\WebRoot\\DataFile";
There is no whole string escape operator but, if it's for file access, you can use a forward slash:
String aa="E:/dev_workspace1/AccessCore/WebRoot/DataFile";
Windows allows both forward and backward slashes as a path separator. It won't work if you pass the path to an external program that mangles with it and fails, but that's pretty rare.
Might not be a direct answer to your question, but I feel this should be pointed out:
There's a system-dependent default name-separator character.
The really system-independent way is to do this:
String aa = "E:/dev_workspace1/AccessCore/WebRoot/DataFile";
String output = aa.replace('/', File.separatorChar);
It will give you
"E:\dev_workspace1\AccessCore\WebRoot\DataFile"
on Windows and
"E:/dev_workspace1/AccessCore/WebRoot/DataFile"
just about everywhere else.
If you write a path, you should use the '/' as path-separator under Java. The '/' is the official path-separator under Java and will be converted to the appropriate separator for the platform (\ under windows, / under unix). The rest of the string is unchanged if passed to the system, so the '\' also works under windows. But the correct way to represent this path is "E:/dev_workspace1/AccessCore/WebRoot/DataFile".
If you want to represent a '\' in a Java-String you have to escape it with another one: "This String contains a \".