This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between String and string
I'm using string for a variable, like this
string myString = "test";
And I'm using String if I want to use some methods(?) of the Class String
String.Format...
I thought this is looking better. Buy some people are doing stuff like
String myString;
string.Format...
Its working. But I don't like this. How can I tell them to stop? Is there "C# rule" for stuff like this? The same thing for int,Int; char,Char; ...
string is a C# alias to System.String.
If writing C#, you should be using the alias, so string.Format and string myString.
Both end up compiled to the same IL and mean the same thing, but C# has its idioms and using the type alias is part of them - in the same way that you would use int and not System.Int32.
Coding guidelines are an important thing if you are working on bigger projects and ensure that you can easily read code written by any of the developer in your team.
Unfortunately there isn't any official guideline on how you should format your C# code. Microsoft itself encountered the problem while developing the .NET framework and developed an internal set of style guidelines which grew into a full fledged program called StyleCop which has a default rule set with sensible settings.
According to these rules you should always use string instead of String:
string xyz;
string.Format();
The rules is the following:
SA1121 - UseBuiltInTypeAlias - Readability Rules
The code uses one of the basic C# types, but does not use the built-in
alias for the type.
Rather than using the type name or the fully-qualified type name, the
built-in aliases for these types should always be used: bool, byte,
char, decimal, double, short, int, long, object, sbyte, float, string,
ushort, uint, ulong.
A recommended reading is the history of StyleCop you can find here:
http://stylecop.codeplex.com/wikipage?title=A%20Brief%20History%20of%20CSharp%20Style&referringTitle=Documentation
It explains some of the problems you encounter with different people from different backgrounds working on the same code base and how they developed the rule set.
We recently implemented StyleCop in our own project and although it is a lot of work to really follow all the rules, the resulting code is much more readable. It also has a fairly good ReSharper integration which allows you to do many fixes automatically if you use ReSharper.
I usually express this as, "If there is an identical primitive type in the language, prefer it." In your specific case, which style to use is a preference rather than something that has major impacts to functionality. What is important is that whatever style is chosen is consistently applied by everyone in your team.
Related
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?
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
I'm working on a VB.NET codebase that uses legacy naming conventions vaguely similar to Hungarian Notiation, for instance:
A member string Test would be mstrTest
A function-scope int Test would be lintTest
A parameter Object Test would be pobjTest
In order to verify that variables are being named correctly, and to work out a solution to each non-conforming variable name, I need to find any instance of variables in the codebase, along with their scope and type.
I've done some tests using regexes to look for Functions and Subs, but instances of class member variables (for instance) would be difficult to do in this way, not to mention that parsing code with Regexes feels incorrect.
Is there a way (in C#) that I could create some kind of structured hierarchy from the codebase without having to start from scratch, or a better way to achieve this tack in general?
Apologies if my explanation is wrong/vague, I've not attempted to parse a language before.
Hungarian notation was considered very bad practice even in the days of VB6. What you are asking require code analysis.
Regex expressions aren't enough. You can use tools like Resharper to find and even rename the variables using its SDK although there may be plugins that already do what you want. In .NET vNext the Roslyn compiler will allow you to do this out-of-the-box. Perhaps you can try VS2015 CTP 6 to create a quick-and-dirty utility if you don't want to use Resharper.
You can start from Roslyn's GitHub repository, it contains several samples that show how to write analyzers, refactorings etc, as well as documentation on syntax and semantic analysis. Also check Kathleen Dollard's RoslynDOM library which simplifies coding significantly
When I use resharper tool, it just says "use built-in type "string" rather than using "String". Similarly, it converts UInt32 to just uint.
I have googled this and all I can find is they are aliases. Aliases meaning "Duplicates". Ok.
But, what exactly do they mean about it ?
When both are same, why the tool suggests using "string" and "uint" for "String" and "UInt32" ?
Also, what is the difference between dot-net types and C# types.
Have googled it but couldnt find any satisfying answers.
Thanks.
The answer given by Rafal sums it up, but there are a couple of clarifications I'd like to make: the only case when using keywords rather than type names is necessary is when defining an enum's underlying type -- In that case, using the latter would not be allowed.
Example:
enum Foo : Int32
{
}
The above won't compile.
Also, while I generally prefer to use keywords, it must be said that while the types are the same for every language running on the .NET Framework, the keywords are different. For example, while in C# long is an alias for Int64, in C++/CLI, long is actually an Int32. That can create some confusion when, for instance, porting code between CLI languages.
String and string are same and so are the UInt32 and uint.
This just due to CLS-compliance, so that you could write C# class library and use in VB program and vice versa.
Some excerpts from MSDN:
To fully interact with other objects regardless of the language they were implemented in, objects must expose to callers only those features that are common to all the languages they must interoperate with. For this reason, the Common Language Specification (CLS), which is a set of basic language features needed by many applications, has been defined. The CLS rules define a subset of the Common Type System; that is, all the rules that apply to the common type system apply to the CLS, except where stricter rules are defined in the CLS. The CLS helps enhance and ensure language interoperability by defining a set of features that developers can rely on to be available in a wide variety of languages.
Please refer Common Language Specification
There is no difference between String and string because as you have pointed out those are aliases - alias is just a different name for the same thing.
As to why Resharper does something you should ask or seek on resharper dedicated site. In my opinion it is merely question of convention - you should use one of those and why not use the one that majority uses.
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