Convert string.Format method call to C# interpolated string - c#

I know that I should probably leave the codebase alone (principle: if it ain't broke...) but the one in question has a lot of calls to string.Format() and I'm intrigued by the new interpolated string support in C# 6.0 as it might make the {0} substitutions less error prone. My aim is to detect and remove execution paths that might have an unused parameter to string.Format() or - worse - an unsubstantiated reference to a parameter that doesn't exist (e.g. {1} if there's only only one parameter).
Do any tools or code snippets exist that might assist in converting all string literals from one format to the other? I'd settle for *.cs files to start, the XAML binding replacements could come later.
Would this exercise be relatively safe (i.e. is there some glaringly obvious flaw with interpolated strings that I haven't considered?)

Related

"String" vs. "string" in quicktip about IsNullOrWhiteSpace()

Working within Visual Studio 2015, I have a conditional check to the effect of:
if(String.IsNullOrWhiteSpace(stringToTest))
And I saw an IDE001 quick tip or action suggesting that the "Name can be simplified" with a suggested correction of:
if(string.IsNullOrWhiteSpace(stringToTest))
With the only difference being to use string instead of String.
MSDN examples use an uppercase S with String, and this SO answer clarifies that "string is an alias in C# for System.String. So technically, there is no difference."
And to be clear, my question relies upon the answers within String vs. string, but I have a different question than what is asked there.
Also related is this SO question, although the answers there don't really address the question. That particular question is very similar to mine, however it is marked as a duplicate of the other SO question I noted. And there is a comment by the OP indicating this is brand new behavior only seen in 2015.
My Question
My question is that if the two variable types are equivalent, and MS examples use the upper case version, why am I seeing quick actions to use the lower case version? Was there a change in the .NET 4.6 framework and VS2015 to encourage using the lower case version? It doesn't seem like I should be seeing that type of a tip.
Well, as smarter than me have noted there's actually no difference in the compiling level, and like you (and like JohnyL as you'll see ;), I also thought it's a bug and got to what's leading me to my answer:
why am I seeing quick actions to use the lower case version?
Taken from this informative (and funny) bug discussion, these are the main points for this feature:
It doesn't just change the letter case, it replaces the String type name with the string keyword. The fact that the 2 happen to differ only by case is a coincidence. There are cases where the number of characters is different (Int32 -> int) or the name is completely different (Single -> float).
Lower case names are easier to type.
For people that actually prefer the consistent format of string in the code (it's probably dependent on other languages you code in and their conventions) this feature helps change existing source code to be consistent.
string is also a keyword with a well defined meaning while String's meaning may be different depending on context.
Was there a change in the .NET 4.6 framework and VS2015 to encourage using the lower case version?
As far as I've read, No.
BTW, you can change this behavior to suit your preference in Tools > Options > Text Editor > C# > Code Style -> Uncheck "Prefer intrinsic predefined type keyword in member access expressions".
I am only speculating, but it seems to me that the quick tip is intended to help you simplify System.String to string, ignoring the fact that your usings have made it redundant, at least in terms of character-counting.
Call it a bug (albeit an extremely minor one) or at least the IDE getting overzealous. One could argue that this is a valid simplification in a broader sense, particularly if you are to use these short "aliases" consistently in your code. As a C++ developer, I'm not really seeing it, but there you go.
There is no difference for compiler but IDE quick fixes are also used for ensuring good styling (e.g. naming conventions). You are programming in C# so you're expected to use its features (in this case - bultin type alias).
I think you are using int instead of Int32, right? So the same is for string and String. Although there is no real difference in length for string technically this is still similar case.
I have a suspicion that the primary reason for changing System.String to string is because it is regarded as a primitive .NET. And since all primitives have aliases - System.Int32 -> int, System.Char -> char etc., for consistency-sake, "string" is treated the same. Looking through all sorts of other MSDN documentation you'll see the two being used interchangeably; I think that's a simple oversight on their part.
Whether its warranted or not, I'm still going to use string over String as the quick tips suggest. Sounds like an example of Grandma's Cooking Secret, but is there a reason to change that behavior in this case?

How to refactor C# interpolated strings to string.Format(...) automatically?

Recently in C# 6 a new language element/syntactic sugar was introduced named string interpolation.
However after a few minutes of enjoying the sweet taste of this syntax, it quickly turns out, that interpolated strings (what are still string literals in semantic point of view) can not be refactored out to a resource because of the variables embedded are living only that scope where the interpolated string is defined.
This scope locked string literals for example can not be localized and regardless of the localization need, some code quality checkers used to regard string literals embedded in as code smell.
Working with a huge enterprise code base I expect to appear more and more interpolated strings, so the problem will be quickly turn from theoretical to practical. I would like both
have a code quality checker rule which bans out this practice just
like string literals in the middle of the code (I can manage it, by
defining custom rules in the standard quality tools. Although StyleCop currently does not even recognize them, and runs to an internal error, so this will not be as easy as it sounds)
have a refactoring tool what can refactor
string interpolation to string.Format so then it can easily can
refactor out to a standard .NET resource.
Any suggestions
Enabling code analysis prevents usage of interpolated strings (warning CA1305) as they don't support specifying locale (unlike String.Format). So while somewhat awkward this is possible solution to your particular case.
Also R# can quickly convert one format to another - so while not automated combination of Code Analysis and R# would let you quickly find and partially correct all the cases.
Localisation is possible with string interpolation.
Consider this:
System.FormattableString s = $"Hello, {name}";
s.ToString() will use the current culture to produce the string.
float flt = 3.141;
System.IFormattable s = $"{flt}";
With IFormattable you can alter numeric formats according to specific languages
So it is possible, just not directly.
source:
https://msdn.microsoft.com/nl-nl/library/dn961160.aspx

c# inline string options - for embedded double quotes

I use the # prefix with my inline strings quite often, to support multi-line strings or to make string with quotes a little more readable. Having to still double up the inline quotes is still somewhat of a pain, so this made me wonder if there was still another option in .net that would allow strings to maintain their doublequotes without requiring some form of delimiting? Something like a CDATA section in xml? I've searched a bit and didn't find anything, but thought I'd ask here in case I've overlooked some .Net feature (perhaps even a recent one in version 4 or 4.5)
update: I've found that vb.net has "XML Literals" that allow defining xml snippets directly inline with the source. This looks pretty close to what I'd like c# to do...
If there was something that would do what you want, than we wouldn't need to "escape" double quotes.
I like to use # when writing dynamic HTML in code. But static strings do belong to resources. Even ones that have dynamic values, for example, "Application error. Error Message: {0}". Then you use string.format to form the output.

outlaw string in c# using intellesence

I often type string in c# when actually I want to type String.
I know that string is an alias of String and I am really just being pedantic but i wish to outlaw string to force me to write String.
Can this be done in ether visual studio intellesence or in resharper and how?
I've not seen it done before, but you may be able to achieve this with an Intellisense extension. A good place to start would be to look at the source for this extension on CodePlex.
Would be good to hear if you have any success with this.
I have always read in "Best Coding Practices" for C# to prefer string, int, float ,double to String, Int32, Single, Double. I think it is mostly to make C# look less like VB.NET, and more like C, but it works for me.
Also, you can go the other way, and add the following on top of every file
using S = System.String;
..
S msg = #"I don't like string.";
you may laugh at this, but I have found it invaluable when I have two similar source codes with different underlying data types. I usually have using num=System.Single; or using num=System.Double; and the rest of the code is identical, so I can copy and paste from one file to the other and maintain both single precision and double precision library in sync.
I think ReSharper can do this!
Here is an extract from the documentation:
ReSharper 5 provides Structural Search and Replace to find custom code constructs and replace them with other code constructs. What's even more exciting is that it's able to continuously monitor your solution for your search patterns, highlight code that matches them, and provide quick-fixes to replace the code according to your replace patterns. That essentially means that you can extend ReSharper's own 900+ code inspections with your custom inspections. For example, if you're migrating to a newer version of a framework, you can create search patterns to find usages of its older API and replace patterns to introduce an updated API.
cheers,
Chris

Streaming structured text input

I'd like to parse formatted basic values and a few custom strings from a TextReader - essentially like scanf allows.
My input might not have line-breaks, so ReadLine+Regex isn't an option. I could use some other way of chunking text input; but the problem is that I don't know the delimiter at compile time (so that's tricky), and that that delimiter might be localization-dependant. For instance, a float followed by a comma might be "1.5," or "1,5," but in both cases attempting to parse the float should be "greedy".
To be safe, I'd like to assume my input is actively hostile (say, streaming in from a network stream): i.e. intentionally missing chunking delimiters.
I'd like to avoid custom Regex's: int.Parse and double.Parse work well and are localization-aware. Don't get me started on DateTime's - I might need a few custom patterns anyhow, but writing Regexes to cover that scenario doesn't sound like fun.
For a concrete example, let's say I have a TextReader and that I know the next value should be a double - how can I extract that double and possibly a limited amount of lookahead without reading the entire stream and without manually writing a localizable double-parser?
Similar Questions
There's a previous question "Looking for C# equivalent of scanf" which sounds similar but the Q+A focus on readline+regex (which I'd like to avoid). How can I use Regex against a TextReader? didn't find an answer (beyond chunking), and in any case I'd like to avoid writing my own Regexes.
Based on that lack of answers and still not having found anything myself, it seems that
There is no means to use localized parsing directly from Streams (or TextReaders) in .NET, nor is there a way to know how much of the stream corresponds to a parseable prefix in a systematic way.
There is no means to apply regular expressions to Streams (or TextReaders) in .NET, so there's no easy way of implementing something like this yourself.
If you really need something like this, the easiest option is a full-fledged parser generator. ANTLR works well for this; it has a lot of existing grammars you can copy-paste for the basics, and it comes with a GUI to help understand your grammar and makes parsers for .NET, java, C and a host of other languages. It's developer friendly, fast... ...but way too powerful and flexible for what I need; like shooting a bug with a shotgun - I'm not thrilled with this solution.

Categories