I used resharper for my asp.net mvc application to format code and it changed all my code with # in DisplayName attribute. I tried searching for this in google to find out what # does here but I cant find satisfactory search result. COuld some on tell me about the difference between with and with out # in displayname attribute.
[DisplayName("Meeting Date")]
[DisplayName(#"Meeting Date")]
The fact that this is being done in an attribute is immaterial. Using the '#' character in front of a string literal is called a verbatim string and causes any escape sequence to be ignored, allowing you to do this:
var filename = #"C:\Filename.ext"
instead of this:
var filename = "C:\\Filename.ext"
Lots of people like that because it is prettier. Resharper likes to put that '#' symbol in front of string literals.
As I recall Resharper suggests you either move localizable strings into a resource file or make them verbatim. In your case, it looks like you accepted the suggestion (either explicitly or via code cleanup) to make a string verbatim. You can turn off the verbatim string suggestion under Resharper --> Options --> Code Editing --> C# --> Context Actions --> Convert to verbatim string.
Actually, I'm NOT sure why ReSharper would have detected an Attribute constructor value as localizable since they must be compile-time constant, so it probably did that based on some other condition. A quick email to support#jetbrains.com should get that sorted out for you pretty quickly.
NOTE: The '#' symbol can also be used in front of a reserved word in order to use that as a variable name, though this is not the case in your example above:
var #string = "string";
Related
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.
I'm using VS 2015 with Resharper Ultimate for a Win Forms application and was doing something as simple as setting the text property of a button when I saw the blue squiggly line below the string.
Clicking on it converts the statement to the one I've retyped just below the problematic statement and there's no blue squiggly. Note that it's got the verbatim and the interpolation operators.
Also, setting the same string to another string with just interpolation seems to work fine. There's no characters to escape in this string. What's happening here?
As for verbatim string: Untick "ReSharper | Options | Code Editing | C# | Localization | Don't analyse verbatim string" checkbox and then ReSharper will show you such kind of suggestion for verbatim string as well.
As for why it shows squiggle for WinForms property but does not for a string: please refer to a webhelp article about "Localizable inspector" property. In case you would like to get the suggestion for all strings as well, you need to change "Localizable inspector" value to "Pessimistic"
You are setting a UI element's text to a string, and UI should be subject to localization.
On the other hand, interpolation is equivalent to just calling string.Format with default format provider.
It is assumed that UI elements will be populated from resources and that they will be formatted using specific culture. That is why ReSharper is sensitive to this particular use of string interpolation.
What you said about setting a different string to the interpolated string and then assigning that to the UI element, you are just playing tricks on ReSharper. It was not able to infer that you have assigned the UI element to the string which is not localized, but the problem is still there.
Have been studying a sample source code and I can't understand this part, what is this piece of code doing? Mostly the RegEx part...
in the parameters used, "code" is a string, it is C# source code we are passing in.
Match m = null;
if ((m = Regex.Match(code, "(?ims)^[/']{2}REFDLL (?<ref>.+?)$")).Success)
{
foreach (string refDll in m.Groups["ref"].Value.Split(new char[] { ';', ',' }))
{
//2008-06-18 by Jeffrey, remove redundant \r
string mdfyRefDll = refDll.Replace("\r", "").Replace("\n", "");
//trim the ending .dll if exists
if (mdfyRefDll.ToLower().EndsWith(".dll"))
mdfyRefDll = mdfyRefDll.Substring(0, mdfyRefDll.Length - 4);
string lcRefDll = mdfyRefDll.ToLower();
if (lcRefDll == "system.data.linq" || lcRefDll == "system"
|| lcRefDll == "system.xml.linq" || lcRefDll == "system.core")
continue;
cp.ReferencedAssemblies.Add(mdfyRefDll + ".dll");
}
}
I think this image addresses what's going on in the code you posted:
Mini C# Lab's project description is as follows:
A handy tool for simple short C# code running and testing, you can
save time on waiting for Visual Studio startup and avoid creating a
lot of one-time only project files.
It seems like that project is missing documentation, so it's difficult to extrapolate why the author of the code chose that particular way to add referenced DLLs when there is a using directive in there already. Perhaps he did it to avoid conflicts with the using statement.
First, (?ims) is specifying options. i triggers case-insensitivity, m specifies multi-line mode, and s (IIRC) enables the dot-all option, meaning that the wildcard . includes newline characters.
Then, ^ asserts, "The string must begin here, with no preceding characters..." while the $ at the end asserts, "The string must end here, with no following characters."
The [/']{2} matches exactly two of either the slash or single-quote characters, i.e. //, '', /', and '/.
The REFDLL matches exactly what you see.
The (?<ref>.+?) matches all remaining characters (the final question mark is unnecessary), and remember, due to the s option, this includes newline characters. This portion is stored in a match named ref.
In summary, it's trying to match something like
//REFDLL helloworld foobar
and stores "helloworld foobar" in ref.
I have a function that builds an anchor tag. The function recieves the URL, Title as parameters. The problem is that sometime the text includes quotation marks and this results in a anchor tag generated with syntax errors.
Which is the best way to solve this problems? Is there any function that parses the text into a safe string, in this case, for the title attribute.
Otherwise I can check the string and strip all quotation marks, but I would like know if there is a better way to do this, e.g there might be some other characters that can crash my function as well.
Actually you want to use HttpUtility.HtmlAttributeEncode to encode your title attribute. The other encoders will do more work (and have different uses) whereas this one only escapes ", &, and < to generate a valid text for an attribute.
Example:
This is a <"test"> & something else. becomes This is a <"Test"> & something else.
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.
""";