I'm looking at the MSDN docs about List.GetEnumerator.
They say the C# method signature is:
public List<(Of <(<'T>)>)>..::..Enumerator GetEnumerator()
I was expecting this much simpler signature:
public List<T>.Enumerator GetEnumerator()
What does their signature mean, with all the punctuation and the "Of" keyword?
Edit: Well, I guess if no one has seen that syntax, then the MSDN docs are just a bit buggy, and that's all.
MSDN uses some code generation to supply that signature for all of the different languages, and this looks like a bug in that code which forgets to take the actual language into account and just outputs all of the syntax - everythign in there can be matched to the expected syntax for such a return type in some language (although, admittedly, I'm not entirely sure where the apostrophe is from).
The same problem can be seen on other pages, such as the very similar HashSet.GetEnumerator, but not on others, like Queryable.AsQueryable, so it seems likely that they don't generate everything at once, and the bug was introduced/removed between the generation of those two pages. (Since we don't know how new each of those are, we can't guess if it's already been fixed.)
I don't know if they have automatic re-generation running every now and then, but if they do, it will probably fix itself soon. If not, you could leave a comment about it in the Community Content section.
Looks like a mistake in MSDN. Take a look at how Queue is defined: http://msdn.microsoft.com/en-us/library/7977ey2c(v=VS.90).aspx
Related
Feel free to edit 'mutate' from the title if it's a poor choice of wording.
My question is, relatively, simple.
Take the following example:
myCollection.OrderBy(o => o);
How do I know whether OrderBy will/will not order myCollection or whether an assignment (following) is necessary:
myCollection = myCollection.OrderBy(o => o);
Is it a case of having to build it and check every time I encounter an extension I'm unfamiliar with?
Please note: I'm not asking whether this will or will not affect myCollection, I already know the answer to that from using it hundreds of times previous, I'm asking how I'd know.
You can't tell from just the signature.
The best you can do is to investigate the actual code, for example by looking at the .NET Reference Source. Another thing you could do is check the return type. If it is the same as the one it's being called on, it probably doesn't change it, it most likely returns a new instance. Is it a void, then it probably does change something inside.
For your specific case for example, OrderBy: no. See here. It 'just' returns a new OrderedEnumerable.
You can check for the Pure attribute in the class decoration as Steven Liekens said. But in its absence, the only way to know for sure is by:
Experimenting: for example, get an instance of the class and serialize it. Use the method and then serialize it. Compare the results. May not be accurate every time.
Reverse engineering the method: and I hope you have the source code. If you don't, you can use reflection. This will require some judgement if the method is somewhat complex, but this complexity here is subjective.
Reading the docs and trusting them - if the doc is present. This is the sensible thing to do with the .NET Framework types, and an exercize of faith otherwise.
One way is to find out if the method or its class is marked as [Pure]. Pure code does not modify input values.
According to General Naming Conventions of .NET framework:
X DO NOT use abbreviations or contractions as part of identifier names.
For example, use GetWindow rather than GetWin.
X DO NOT use any acronyms that are not widely accepted, and even if they are, only when necessary.
I've once consider GetName can be used for my method, but I believe it's not so sematically meaningful.
In order not to deviate too far from the naming convention, I've tried to figure out widely accepted acronyms, but I just run out of ideas for the following method:
String GetExplicitInterfaceMemberImplementationName(MemberInfo info) {
return info.DeclaringType.Name+"."+info.Name;
}
For this case, it is, in fact, not really longer than the statement, but just the identical length; and Type.Delimiter should be used rather than ".". However, the naming problems so often bothers me.
So, what method name should I declare? And for the long-term solutions, what can I do?
For an additional question, is there an API out of the box does the same thing?
Edit 1:
Stop and think, such a good suggestion for me.
For the purpose of its statement, also for semantic and not breaking the naming conventions, I got an idea from [AddAttributeStoreCommand.TypeQualifiedName Property]; so I now declare it as:
public static String GetTypeQualifiedName(this MemberInfo info) {
return info.DeclaringType.Name+"."+info.Name;
}
Yet, a long-term solution hasn't come up ..
Edit 2:
I'm not sure whether it's a good practice to name like this ..
public static String GetTypeDotItsName(this MemberInfo info) {
return info.DeclaringType.Name+"."+info.Name;
}
Code Complete 2nd Edition has this to say about method name length:
Make names of routines as long as necessary
Research shows that the optimum average length for a variable name is 9 to 15 characters. Routines tend to be more complicated than variables, and good names for them tend to be longer. Michael Rees of the University of Southampton thinks that an average of 20 to 35 characters is a good nominal length (Rees 1982). An average length of 15 to 20 characters is probably more realistic, but clear names that happened to be longer would be fine.
Note the word average. If the method name is as clear as possible, and it's 50 characters, then whatever. It's fine.
However, the book does mention another thing a few paragraphs up:
If you have routines with side effects, you’ll have many long, silly names, The cure is not to use less-descriptive routine names; the cure is to program so that you cause things to happen directly rather than with side effects.
Of course, side effects aren't the issue here, but you can extend the idea. Ask yourself "Is this long, silly name popping up because I'm doing overly complicated stuff?" If you're sure that you need an ExplicitMemberInterfaceImplementationName, then fine, but it can at least be something to stop and think about.
1) Put in the information that is needed to make the purpose of the method clear. You can probably halve the length of your example name without any loss of understanding about what it fits.
2) guidelines are guidelines. Don't slavishly follow rules when they become counter productive. If using an abbreviation makes it easier to read and understand the code, use abbreviations. The main thing is to try to limit abbreviations to long names that are commonly used, and use intuitive and commonly used abbreviations for them, so that anyone reading your code can easily work out what they mean. For example, decl is a common abbreviation for declaration, and difficult to mistake for anything else.
3) sometimes you can avoid the need to abbreviate by using a synonym.
I think you could probably drop interface and member from your name without losing the meaning.
But perhaps the "explicit interface implementation name" is actually the "explicit name" - explicit has a well defined meaning, especially in the context if your class, and you can always add the fully watertight legal definition in your documentation comment. So: "GetExplicitName"
Is it a good practice to start a method name with "Does" (in C#)? It looks a little bit weird to me, so I would like to get your opinion.
I am writing a method which check if an account exists or not, should the signature be
"bool DoesAccountExist(id)"? Is there a better name?
Thanks!
Personally I'd go with AccountExists(id) in this case, since it will look more natural in an if block
if (AccountExists(id)) { }
We always use Is for any method that will return a boolean, so in this case we would call the method
IsExistingAccount(id)
I usually leave off the Does and simply use AccountExists(id).
To me it looks more natural later in code such as:
if(AccountExists(id))
{
ValidateLogin();
}
The alternative would be something like:
if(!DoesAccountExist(id)) {}
seems odd to me. I would read that as if does account not exist? Which makes less then account does not exist.
The "Is" prefix idiom help clarify methods like Array "Empty" which might mean "empty the array" or "is the array empty?". If used consistently "IsEmpty" is clearly the bool return and by convention "Empty" becomes clear as the action of emptying.
In the context of the question I agree with #Andy Whites second suggest:
if (IsExitingAccount) ...
Here the 'Is' triggers a strong automatic implication of bool return constistant with its use else where (IsEmpty, IsNull, etc)
I think AccountExists is your best bet, but one other option is: IsExistingAccount. For methods or properties that return a boolean, it can be useful to use a naming convention where the method begins with the word "is". If you use "is," you'll have to rephrase the rest of the method name so that it makes sense to the reader.
Can or Is could be used like CanCopy or IsAccountExists is fine too. Following predefined conventions make code more readable. To be frank Does prefix looks a bit wierd to me as well.
Another Option is to use the standard C# plural of Is, Any.
AnyAccountsExist(id)
When using extremely short-lived objects that I only need to call one method on, I'm inclined to chain the method call directly to new. A very common example of this is something like the following:
string noNewlines = new Regex("\\n+").Replace(" ", oldString);
The point here is that I have no need for the Regex object after I've done the one replacement, and I like to be able to express this as a one-liner. Is there any non-obvious problem with this idiom? Some of my coworkers have expressed discomfort with it, but without anything that seemed to be like a good reason.
(I've marked this as both C# and Java, since the above idiom is common and usable in both languages.)
This particular pattern is fine -- I use it myself on occasion.
But I would not use this pattern as you have in your example. There are two alternate approaches that are better.
Better approach: Use the static method Regex.Replace(string,string,string). There is no reason to obfuscate your meaning with the new-style syntax when a static method is available that does the same thing.
Best approach: If you use the same static (not dynamically-generated) Regex from the same method, and you call this method a lot, you should store the Regex object as a private static field on the class containing the method, since this avoids parsing the expression on each call to the method.
I don't see anything wrong with this; I do this quite frequently myself.
The only exception to the rule might be for debugging purposes, it's sometimes necessary to be able to see the state of the object in the debugger, which can be difficult in a one-liner like this.
If you don't need the object afterwards, I don't see a problem - I do it myself from time to time as well. However, it can be quite hard to spot, so if your coworkers are expressing discomfort, you might need to put it into a variable so there are no hard feelings on the team. Doesn't really hurt you.
You just have to be careful when you're chaining methods of objects that implement IDisposable. Doing a single-line chain doesn't really leave room for calling Dispose or the using {...} block.
For example:
DialogResult result = New SomeCfgDialog(some_data).ShowDialog();
There is no instance variable on which to call Dispose.
Then there is potential to obfuscate intent, hurt rather than improve readability and make it tougher to examine values while debugging. But those are all issues particular to the object and the situation and the number of methods chained. I don't think that there is a single reason to avoid it. Sometimes doing this will make the code more concise and readable and other times it might hurt for some of the reasons mentioned above.
As long as you're sure that the object is never needed again (or you're not creating multiple instances of an identical object), then there's no problem with it.
If the rest of your team isn't comfortable with it, though, you might want to re-think the decision. The team should set the standards and you should follow them. Be consistent. If you want to change the standard, discuss it. If they don't agree, then fall in line.
I think thats ok, and would welcome comments/reasons to the contrary. When the object is not short lived (or uses unmanaged resources - ie COM) then this practice can get you into trouble.
The issue is readability.
Putting the "chained" methods on a separate line seems to be the preferred convention with my team.
string noNewlines = new Regex("\\n+")
.Replace(" ", oldString);
One reason to avoid this style is that your coworkers might want to inspect the object in a debug mode. If you compound the similar instantiation the readability goes down a lot. For example :
String val = new Object1("Hello").doSomething(new Object2("interesting").withThis("input"));
Generally I prefer using a static method for the specific example you have mentioned.
The only potential problem I could see is - if, for some reason, new Regex were NULL because it was not instantiated correctly, you would get a Null Pointer Exception. However, I highly doubt that since Regex is always defined...
If you don't care about the object you invoke the method on, that's a sign that the method should probably be static.
In C#, I'd probably write an extension method to wrap the regex, so that I could write
string noNewlines = oldString.RemoveNewlines();
The extension method would look something like
using System.Text.RegularExpressions;
namespace Extensions
{
static class SystemStringExtensions
{
public static string RemoveNewlines(this string inputString)
{
// replace newline characters with spaces
return Regex.Replace(inputString, "\\n+", " ");
}
}
}
I find this much easier to read than your original example. It's also quite reusable, as stripping newline characters is one of the more common activities.
I'm having a little bit of trouble understanding what the problem is here. I have a bit of code that pulls records from a database using LINQ and puts them into an object which is cast into an interface. It looks a bit like this:
public IEnumerable<ISomeObject> query()
{
return from a in dc.SomeTable
select new SomeObject
{
//Assign various members here
} as ISomeObject;
}
When I test this, I put the returned IEnumerable into a variable called results and run this line:
Assert.AreEqual(EXPECTED_COUNT, results.Count());
When this is run, I get a System.Security.VerificationException: "Operation could destabilize the runtime."
I found the solution here, which is this:
var results = from a in dc.SomeTable
select new SomeObject
{
//Assign various members here
} as ISomeTable;
return results.OfType<ISomeObject>();
This works, but I'm having trouble understanding what's happening here. Why did I get the exception in the first place and how did the lines of code above fix it? The MSDN documentation seems to suggest that this is an issue of type safety, but I'm not seeing where the previous code was type-unsafe.
UPDATE
A little bit more information I found out. The first example works if I make the return type IQueryable. This sheds a little bit more light on what was going wrong, but I'm still confused about the why. Why didn't the compiler force me to cast the IEnumerable into an IQueryable?
I believe it is an issue of covariance or contravariance as noted by this forum post.
See Covariance and Contravariance in C#, Part Two: Array Covariance and the rest of the Covariance and Contravariance series at Eric Lippert's blog.
Although he is dealing with Arrays in the article I linked, I believe a similar problem presents itself here. With your first example, you are returning an IEnumerable that could contain objects that implement an interface that is larger than ISomeTable (i.e. - you could put a Turtle into an Animals IEnumerable when that IEnumerable can only contain Giraffes). I think the reason it works when you return IQueryable is because that is larger/wider than anything you could return, so you're guaranteed that what you return you will be able to handle(?).
In the second example, OfType is ensuring that what gets returned is an object that stores all the information necessary to return only those elements that can be cast to Giraffe.
I'm pretty sure it has something to do with the issues of type safety outlined above, but as Eric Lippert says Higher Order Functions Hurt My Brain and I am having trouble expressing precisely why this is a co/contravariant issue.
I found this entry while looking for my own solution to "operation could destabilize the runtime". While the covariance/contra-variance advice above looks very interesting, in the end I found that I get the same error message by running my unit tests with code coverage turned on and the AllowPartiallyTrustedCallers assembly attribute set.
Removing the AllowPartiallyTrustedCallers attribute caused my tests to run fine. I could also turn off code coverage to make them run but that was not an acceptable solution.
Hopefully this helps someone else who makes it to this page trying to find a solution to this issue.
Just a guess, but the as operator may return a null - so it may have to do with the actual implementation of the new SomeObject { ... } code, since it's syntactic sugar. The return results.OfType<ISomeTable>(); filters based on type, so your method's return statement will only return that type (ensuring type safety). I've run into a similar issue with returning generic types.
P.S. I love the "Operation could destabilize the runtime." exception. That's almost like the "You might blow up the internet" exception.
I came across this error with similar code;
IEnumerable<Table> records = (from t in db.Tables
where t.Id.Equals(1)
select t).ToList();
This seemingly harmless code was part of a UserControl method which was called from a Page. No problem in a .NET4 development environment, however, when the site was PreCompiled and deployed to the server on .NET3.5 I got this error.
I suspect this has something to do with the fact that the control was being compiled into a separate DLL combined with the security changes between the frameworks as described in this .NET security blog
My solution: run the live site on .NET4
`I have added to web.config file in section then System.Security.VerificationException: "Operation could destabilize the runtime." not coming for me.
<system.Web>
<trust level="Full"/>
Does it still fail if you change this:
select new SomeObject { ... } as ISomeTable;
to this:
select (ISomeTable) new SomeObject { ... };
?
If so (as I see you've confirmed), perhaps this has to do with the fact that an interface implementation could be either a class or a struct? Does the problem still appear if you cast to an abstract class rather than an interface?
I found that OfType had some nasty side effects when using linq to sql. For example, parts of the linq that were previously evaluated after the query was run against the db were instead translated to SQL. This failed as those sections had no SQL equivalent. I ended up using .Cast instead which seems to solve the problem as well.
In my case i had wrongly declared the Storage property in the Column attribute of a Linq2SQL class
[Column(Storage = "_Alias", DbType = "NVarChar(50)")]
public string UserAlias
I had same problem, but with inheritance
I defined a class in assembly A and a subclass in Assembly B
after I added below attribute to assembly A, problem solved:
[assembly: SecurityRules(SecurityRuleSet.Level1, SkipVerificationInFullTrust = true)]
I ran into this error while using the "Dynamic data access framework" Passive library. The source of the error was line 100 in the DynamicDatabase.cs file.
databaseDetectors = (databaseDetectors ?? Enumerable.Empty<DatabaseDetector>()).DefaultIfEmpty(new DatabaseDetector());
I changed that line of code to:
databaseDetectors = (databaseDetectors ?? Enumerable.Empty<DatabaseDetector>()).DefaultIfEmpty(new DatabaseDetector()).OfType<IDatabaseDetector>();
Doing so resolved the problem. I went ahead and forked the project and submitted the change to the original author.
Thank you, Jason Baker, for pointing out the solution in your original question.
On a side note, the original library ran fine on my local machine and on a Rackspace VPS, but when I pushed the same code to a shared hosting environment (GoDaddy and Rackspace's Cloud Sites), I began getting the "Operation could destabilize the runtime" error.
I guess, Linq to Sql may not support casting when translate to sql statement.