which version of C# to use $ instead of string.format - c#

I find a piece of code like this
int a = 100;
string str = $"{a:0.00}";
Console.WriteLine(str);
the result is "100.00"
The $ have the same function of string.Format, and I want to know which version of C#.

This is called string interpolation, and it's part of C# 6, which was released in July as part of Visual Studio 2015.

A C# 6.0 feature, string interpolation.

Related

Printing out MAC address

Just trying to use string.Format() to convert system MAC address to text format. But it's not working:
byte[] MacAddr = new byte[6];
// this works, but rather clumzy
mac = string.Format("{0:X2}-{1:X2}-{2:X2}-{3:X2}-{4:X2}-{5:X2}",
MacAddr[0], MacAddr[1], MacAddr[2], MacAddr[3], MacAddr[4], MacAddr[5]);
// give me index error
mac = string.Format("{0:X2}-{1:X2}-{2:X2}-{3:X2}-{4:X2}-{5:X2}", MacAddr);
Edit1: OK, I am wrong, but it seems string.format works for this guy's case with string[] .
I can see there is a overload method for string.format:
Format(String, array<Object>[]()[]). Is it possble to create some form of byte[], that can be taken as this array<Object>[]()[] ?
the error occurs because you want to format 6 items but there is only 1 in your parameter list
//6 parameters expected, only one "MacAddr" given
mac = string.Format("{0:X2}-{1:X2}-{2:X2}-{3:X2}-{4:X2}-{5:X2}", MacAddr);
here is a shorter version compared to your working approach
mac = string.Join("-", MacAddr.Select(x => x.ToString("X2")));
This is because you specify a format with 6 parameters but provide only one:
//expected 6 parameters, provided only one
mac = string.Format("{0:X2}-{1:X2}-{2:X2}-{3:X2}-{4:X2}-{5:X2}", MacAddr);
if you are working with C# 6.0, you can also work with string interpolation:
//string interpolation
mac = $"{MacAddr[0]}:X2-{MacAddr[1]}:X2-{MacAddr[2]}:X2-{MacAddr[3]}:X2-{MacAddr[4]}:X2-{MacAddr[5]}:X2";
There is only 1 parameter in your string.Format() function while it requires 6 parameters as per requirement.
You can use String.Join for a better readable approach -
mac = string.Join("-", MacAddr.Select(x => x.ToString(":X2")));
try BitConverter
mac = BitConverter.ToString(MacAddr);
BitConverter.ToString(byte[]) gets the exact string you want, although MAC addresses are usually separated by colons, not dashes.

C# 6.0, .NET 4.51 and VS2015 - Why does string interpolation work?

After reading the following:
CLR Needed for C# 6.0
Does C# 6.0 work for .NET 4.0
it seemed to me that aside from String Interpolation any project I compiled in VS2015 against .NET 4.51 could use the new C# language features.
However I tried the following code on my dev machine using VS2015 targeting 4.51:
string varOne = "aaa";
string varTwo = $"{varOne}";
if (varTwo == "aaa")
{
}
and not only did I not receive a compiler error, it worked as varTwo contained aaa as expected.
Can someone explain why this is the case as I would not have expected this to work? I am guessing I am missing what FormattableString really means. Can someone give me an example?
As mentioned in the comments, string interpolation works in this case as all the new compiler does is convert the expression into an "equivalent string.Format call" at compile time.
From https://msdn.microsoft.com/en-us/magazine/dn879355.aspx
String interpolation is transformed at compile time to invoke an equivalent string.Format call. This leaves in place support for localization as before (though still with traditional format strings) and doesn’t introduce any post compile injection of code via strings.
The FormattableString is a new class allows you to inspect the string interpolation before rendering so you can check the values and protect against injection attacks.
// this does not require .NET 4.6
DateTime now = DateTime.Now;
string s = $"Hour is {now.Hour}";
Console.WriteLine(s);
//Output: Hour is 13
// this requires >= .NET 4.6
FormattableString fs = $"Hour is {now.Hour}";
Console.WriteLine(fs.Format);
Console.WriteLine(fs.GetArgument(0));
//Output: Hour is {0}
//13
Can someone explain why this is the case as I would not have expected this to work?
This works since you're compiling with the new Roslyn compiler which ships with VS2015, and knows how to parse the string interpolation syntactic sugar (it simply calls the proper overload of string.Format). If you'd try to take advantage of .NET Framework 4.6 classes that work nicely with string interpolation, such as FormattableString or IFormattable, you'd run into a compile time error (unless you add them yourself. See bottom part of the post).
I am guessing I am missing what FormattableString really means.
FormattableString is a new type introduced in .NET 4.6, which allows you to use the new string interpolation feature with a custom IFormatProvider of your choice. Since this can't be done directly on the interpolated string, you can take advantage of FormattableString.ToString(IFormatProvider) which can be passed any custom format.

How do you enter quote characters in C# 6.0 string interpolations

Given
IDictionary<string, string> x;
previously you could do (as an example of the parameter code having quote marks):
string.Format("{0}", x["y"]);
What is the proper way to format the C# 6.0 string interpolation?
$"{x["y"]}" // compiler error due to the quotes on the indexer value
// UPDATE: actually does work, must have had another typo I missed
Escaping the quotes as
\"
doesn't work, and doing
var b = "y";
...
$"{x[b]}"
seems awkward.
This works for me:
var dictionary= new Dictionary<string, string>();
dictionary.Add("x","value of x");
Console.WriteLine($"x is {dictionary["x"]}");
Make sure your project is set to use the version 6.0 of C# Language level (it's the default option on VS2015).
Edit: You can also try it here. (make sure you check the "C# 6.0 Beta").

Replace text in Visual Studio Regular expression

Recently I convert some of my old codes from vb.net to C#.
I need to change all my existing codes using visual studio regular expression (find & replace dialog inside Visual studio 2010 IDE)
Find
Rows(0).Item(0).ToString()
Replace with
Rows[0][0].ToString()
that means Rows(--any--).Item(--any--).ToString()
to
Rows[--any--][--any--].ToString()
I searched a lot but I am still not able to do this.
Tip: I am using visual studio 2010
My old vb.net code is
Dim firstColumnValue As String = dataTable.Rows(0).Item("firstColumn")
Dim secondColumnValue As String = dataTable.Rows(0).Item("secondColumn")
When i am converting VB.net to C#, i got the following using this plugin, i got this.
var firstColumnValue= dataTable.Rows(0).Item("firstColumn").ToString();
var secondColumnValue = dataTable.Rows(0).Item("SecondColumn").ToString();
But i actually wants like below.
var firstColumnValue= dataTable.Rows[0]["firstColumn"].ToString();
var secondColumnValue = dataTable.Rows[0]["SecondColumn"].ToString();
That vb.net to C# conversion tool converts almost all are fine but i need the above change in almost all files.
Regex:
Rows\(([^)]*)\)\.Item\(([^)]*)\)(\.ToString\(\))
Replacement string:
Rows[\1][\2]\3
DEMO
Example:
string str = "foo bar Rows(0).Item(0).ToString() barfoo";
string result = Regex.Replace(str, #"Rows\(([^)]*)\)\.Item\(([^)]*)\)(\.ToString\(\))", "Rows[$1][$2]$3");
Console.WriteLine(result);
Console.ReadLine();
IDEONE
Find:
Rows\({([^)]*)}\)\.Item\({([^)]*)}\)(\.ToString\(\))
Replace:
Rows[\1][\2]\3
Use:
find : Rows({\d*}).Item({\d*}).ToString()
replace with : Rows[\1][\2].ToString()
and check Use Regular Expression in the search/replace window
You can use Microsoft Visual Studio to convert code from VB to C#.
You can use a free plug-ins like this one This simple plug-in for Visual Studio 2010/2012 allows you to convert VB.net code to C#
Also this regex solutions below are not so perfect. For example: a function call inside parentheses, like "foo bar Rows(0).Item(myfunc(n)).ToString() barfoo";

Visual Studio change C# method parameter colouring

In Visual Studio 2013, is there a way to change the syntax colouring of C# method parameters?
e.g. Can I have AAA and BBB colored, but not someInt, Foo, ToString
private int MyMethod(int AAA, int BBB)
{
int someInt = new int();
someInt = AAA + BBB;
string Foo = AAA.ToString();
}
I tried going to Tools -> Options -> Environment -> Fonts and Colours -> Text Editor and changing Identifier, but this changed the coloring of just about everything (variables, methods, parameters).
ReSharper can do this.
First, check this in ReSharper options:
Then choose the color in the VS options:
End result:
I recently found this extention while looking for the same thing for TypeScript, apparently it supports C# and VisualBasic, so it may be helpful for you and anybody else looking:
Visual studio SemanticColorizer
For VS 2017 you can use.
Enhanced Syntax Highlighting by Stanislav Kuzmich
https://marketplace.visualstudio.com/items?itemName=StanislavKuzmichArtStea1th.EnhancedSyntaxHighlighting
Now you can do this in Visual Studio without any extension.
Here is VS 2022
Unfortunately, you will not find a way to colorize parameter variables with the C# language. You do have the option, however, of writing an extension to do just that. Or, you could rewrite everything in C++, where you can get your parameters colorized.

Categories