标签云

微信群

扫码加入我们

WeChat QR Code


This could be changed quite easily to be null-safe as well: var isEqual = String.Equals(a, b, StringComparison.OrdinalIgnoreCase);

2018年10月22日35分22秒

But... this isn't a C# feature, it is a feature of the .Net framework, more specifically a feature of the class "String"

2018年10月21日35分22秒

this is because anonymous types are not anonymous after compilation.

2018年10月22日35分22秒

Every time I'm dealing with decimals, I have to look up the m. Is it only me or is m not really intuitive? :)

2018年10月22日35分22秒

The M syntax comes from the old VB type called Money. M == Money == Decimal.

2018年10月21日35分22秒

is there one for byte?

2018年10月22日35分22秒

Nope, anything less than an Int32 is automatically inferred by the compiler based on the type to the left of it

2018年10月21日35分22秒

Nick: nice - I like learning the historicals behind the code.

2018年10月21日35分22秒

I'm curious what the compiler spits out for both implementations. The first one definitely looks cleaner and is a cute way of doing it. Could be slower though if the object is actually created in memory first then iterated through.

1970年01月01日00分03秒

But you can have the best of both worlds (at least for this example, or for any integral type) using switch. Example follows, but readability suffers in comments due to lack of newlines: switch(fruit){ case "apple": case "orange": case "banana": case "pear": return true; default: return false; }

2018年10月21日35分22秒

P Daddy - true, but does suffer from a lot of additional syntax. Fowl - you can have fallthrough if the cases have no code (until the fallen-through case of course).

2018年10月22日35分22秒

public static bool In<T>(T value, params T[] items){ return items.Contains(value); } if (fruit.In("apple", "orange", "banana", "pear")) { ... }

2018年10月21日35分22秒

Belorus I think you're treating it as if readability were a science, which it is not. Yes, it is a performance hit, but very often it will make no difference to the overall performance of the program. How is it 'wrong' if it does the job, even if it needlessly allocates memory? Readability is a very subjective thing - what seems simple to one person can seem appalling to another.

2018年10月22日35分22秒

I use this regularly for writing unit tests against internal members of another assembly. That way unit tests can be excluded from deployments.

2018年10月22日35分22秒

This is definitely my best discovery from this topic. The best solution I had found on my own to give unit tests in a different assembly access to internal methods was to make the methods protected and write pseudo-mock classes in my test assembly that inherited from the class being tested.

2018年10月22日35分22秒

InternalsVisibleTo is very useful for exposing a protected internal parameterless .ctor to a NHibernate layer whilst hiding it from a user application which can then only use the public .ctor that enforces supplying required data.

2018年10月21日35分22秒

What's the problem with making your own util method that returns this: (myString ?? "").Trim() == ""

2018年10月22日35分22秒

Charlie Isn't a carriage return treated as whitespace too?

2018年10月22日35分22秒

I definitely prefer Haack's approach now that I have tried it out. You put together string extensions methods for AsNullIfEmpty and AsNullIfWhiteSpace. By doing it this way, you can then use the result in a coalescing operator: SomeString.AsNullIfEmpty() ?? "default value".

2018年10月21日35分22秒

I really don't like "". You should use string.Empty (myString ?? string.Empty).Trim() == string.Empty as it conveys a bit more.

2018年10月21日35分22秒

On the record, I absolutely HATE string.Empty. What could it ever be besides ""? The performance benefit of a static field vs an interned string will be negligible: stackoverflow.com/questions/263191/…

2018年10月22日35分22秒

not for Debug.WriteLine though cuz it uses a #if DEBUG statement internally.

2018年10月21日35分22秒

AndyC: It's not about that here (ForEach is simply defined as a custom extension method somewhere. There are religious debates over that elsewhere :))

2018年10月22日35分22秒

IMHO, the following looks better ----------------- foreach(string s in myString) Console.WriteLine(s);

2018年10月22日35分22秒

I found that TransactionScope aggressively promotes transactions to distributed mode which uses DTC. When DTC becomes involved you'll probably have to deal with DCOM security. I tend to avoid the pain by using native transactions.

2018年10月22日35分22秒

That List.ForEach is faster than foreach or for(;;) is completely bonkers. ForEach uses a method/function delegate to implement the behavior. This is first of all, means worse cache locality because the code is generally executed further away (in memory) from the actual loop. Secondly all you really need to do to verify that this is slower is to look a the generated native code. There's a lot more stuff going on with List.ForEach than you might think.

2018年10月22日35分22秒

Completely bonkers? Well, I found .ForEach to be faster than all other options. See jerrytech.blogspot.com/2010/02/… if you doubt me. Always doubt me ;) The code's there - run it yourself and see.

2018年10月22日35分22秒

On the other hand, Patrick Smacchia says the opposite: ForEach is slower than For. codebetter.com/blogs/patricksmacchia/archive/2008/11/19/…

2018年10月22日35分22秒

There's now also String.IsNullOrWhitespace

2018年10月22日35分22秒

Another benefit of TryGetValue is that if your dictionary is synchronized, there is no race condition. Compared to ContainsKey where another thread could remove the item you are looking for between calls.

2018年10月22日35分22秒

TryGetValue throws if the key is null -- so much for avoiding axceptions. I use a TryGetValue2() extension method to get around this problem.

2018年10月21日35分22秒

Looking up a null in a dictionary seems more likely a code error than looking up a non-existent value. I personally am glad that it throws the exception ;)

2018年10月21日35分22秒

This is similar to reg expressions, very useful, but I can't remember them either. I handle stuff like above with padleft and padright.

2018年10月22日35分22秒

Cool, I never knew it was possible... Is it documented anywhere ?

2018年10月21日35分22秒

Thomas: It's documented in MSDN in the "The ";" Section Separator" section towards the end of the Custom Numeric Formatting topic at: msdn.microsoft.com/en-us/library/0c899ak8.aspx

2018年10月21日35分22秒

No, lets forget it. ;)

2018年10月21日35分22秒

No, lets abuse it till kingdom come. ;)

2018年10月21日35分22秒

Yeah, don't forget it--make sure to nuke it when you have a chance!

2018年10月21日35分22秒

+1. How do you break out from multiple levels of loops without messing with bool variables or moving the entire thing to a function or lambda? There should be a reason why does it exist in the language...

2018年10月21日35分22秒

Two or three levels deep in nested loops and this is an absolute godsend. Can't think of any other possible legitimate reason to use it though.

2018年10月21日35分22秒

Nice tip. You should move this question to the Hidden .NET Base Class Library question stackoverflow.com/questions/122784/…

2018年10月21日35分22秒

Awesome. I've got a multicore webserver; its extra core and memory have been going to waste!

2018年10月22日35分22秒

This optimization works well for me on IronScheme too :)

2018年10月22日35分22秒

On server SKUs of Windows (Server 2003, etc) the default is to use the server GC. The workstation GC is the default on client SKUs such as Vista.

2018年10月22日35分22秒

Instead of 32767 and a comment, how about short.MaxValue?

2018年10月22日35分22秒

Just reminding everyone what the exact MaxValue is!

2018年10月22日35分22秒

perhaps we should list '32767' as the max value for a short as a hidden language feature of itself? (I think it is hidden programmer ethics to hardcode the number)

2018年10月21日35分22秒

Although I used this thing cross classes, I never thought of using it in the same class. I have been looking all over the place for something like that! Great!

2018年10月21日35分22秒

That's great. I always used that calling the base, but never knew you could use it in the same class!

2018年10月22日35分22秒

can you guys link to somewhere showing a usage example of this for cross class and base class?

2018年10月21日35分22秒

I think you meant: public Example(int value1) : this(value1, "Default Value") { }

2018年10月21日35分22秒

Well spotted rball! 1 year, 21 upvotes and nobody spotted my deliberate mistake ;) Fixed.

2018年10月21日35分22秒

Unfortunately, stackalloc requires unsafe context.

2018年10月22日35分22秒

Interesting Visual Studio feature, but the question is about C#.

2018年10月21日35分22秒

+1 There is a section "Visual Studio Features" in this question, where your answer fits perfectly.

2018年10月22日35分22秒

it is named virtual space.

2018年10月21日35分22秒

It's not just Visual Studio feature. you can do this in Microsoft Word Notepad2 etc. etc.

2018年10月21日35分22秒

VS2010 lets you not only select, but edit text in this fashion - such as adding the word "private" to the beginning of every line simply by alt-selecting the space before the lines and starting to type - thereby correcting a poor practice of leaving off the word on multiple field declarations at the same time.

2018年10月21日35分22秒

Why not do this Console.WriteLine( "".PadRight( 22, '-' ) );

2018年10月21日35分22秒

To achieve shorter and cleaner code, for example.

2018年10月22日35分22秒

Hey, this is not exactly true. The volatile keyword instructs the compiler to generate an acquire-fence on every read from a field, and a release-fence on every write to the field. An acquire-fence prevents other reads/writes from being moved before the fence; a release-fence prevents other reads/writes from being moved after the fence. Read more here: bit.ly/hycbVI

2018年10月21日35分22秒

I used params for forbidding the empty constructor in classes: stackoverflow.com/questions/6273404/…

2018年10月22日35分22秒

These are all good ideas. This site generally prefers one idea per answer so they can be rated individually. I would have given you three ratings :)

2018年10月22日35分22秒

[MethodImpl(MethodImplOptions.Synchronized)] = lock(this) = bad

2018年10月22日35分22秒

I'm not familiar with "Sychronized" method, can you tell me what they do?

1970年01月01日00分03秒

"you force anything that inherits from this interface to contain a parameterless constructor" Strictly speaking, no you don't - you force any class that implements your interface to prove that it know the name of a class that implements the interface and has a parameterless constructor. That's not the same thing. class A : SomeObject<A> { public A() // required } class B : SomeObject<A> { } // will compile fine, no constructor.

2018年10月22日35分22秒

Matt, in this case, synchronised (or the methodimpl attribute) locks on the current object while the method is processing. However, the attribute causes a lock(this) while it does it: and in CLR via C# I recall that this was not a good idea (iirc, it exposed a potential security vulnerability but the book is all the way on the other side of the house, and it's really late). This is why most people will lock on a private object member variable instead of lock(this).

2018年10月22日35分22秒

That's awesome! I didn't knwo that... However, same thing with collection initializers... all you need is an Add(x) method. public class MyList{ public void Add(string s){} }. You can then do var l = new MyList{"a", "b", "c"};...

2018年10月22日35分22秒

JohnGibb: Having only an Add method is not sufficient. From section 7.6.10.3 of the C# spec: "The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or a compile-time error occurs."

2018年10月22日35分22秒

No need to lock as all the static members are thread safe.

2018年10月22日35分22秒

Actually there was an internal web service that also could be used to change the value of connectionString too. So the lock was needed, no? I didn't remove the lock because I just copied the code and then added the comment.

2018年10月22日35分22秒

Okay, I completely removed the example and made everything more clear (I hope!).

2018年10月22日35分22秒

nils_gate: No, that's a nasty mistake. You probably think this because MSDN docs often say "static members of SoAndSo class are thread safe." This is not because they're intrinsically thread safe. Quite the opposite, in fact. Since any thread can access static members without even having to share an object reference, then static members are more likely to find themselves in a race condition, which is why Microsoft has taken the trouble to make most of their static members thread safe.

2018年10月22日35分22秒

&quotStatic constructors are also useful when creating wrapper classes for unmanaged code&quot, how about static destructor for unmanaged code? ;)

2018年10月22日35分22秒

Beware! DebuggerStepThrough is very handy, but should only be used on trivial implementations. When you are debugging, methods marked with this attribute are skipped entirely by the debugger as if they aren't there (which hides the implementation details from you as you will single step right past it). Breakpoints inside the method won't ever be triggered.

2018年10月22日35分22秒

Hmm...neat trick but I think I'd take fields being visible in the debugger over having all that cruft in my class

2018年10月21日35分22秒

Plus if this causes you to miss even one bug ever, it won't have been worth your time.

2018年10月22日35分22秒

the usefulness of [DebuggerBrowsable(DebuggerBrowsableState.Never)] is for long database calls for objects like users that have Invoices, Addresses, Phones, CreditCards, etc that are each calls to fill up via database calls. If anyone of these fails to return in time, the whole state of the object returned is unreadable (in the debugger).

2018年10月21日35分22秒

Sweet, great tips, in the last one you had tag trouble... replace < with &lt; and we will be able to read it :)

2018年10月21日35分22秒

Now most of this comes down to 'people don't know the mechanics behind threading' IMHO. That may be true, but doesn't come close to 'hidden language features'? Thumbs up for Debugger.Break()

2018年10月21日35分22秒

I'm not having any luck getting the 2nd one to compile? is it .net 3.5 only? public int eye { get; set; } private void testClosure() { var i = 0; bool changed = false; Action<Action> setAndTagChanged = (action) => { changed = true; action(); }; setAndTagChanged(eye=1); }

1970年01月01日00分03秒

Lambdas are only available in C# 3.0 or greater. That means you must have .Net 3.5.

2018年10月22日35分22秒

Thanks, luckily we've moved up to .net 3.5 thanks to my pushing for it

2018年10月22日35分22秒

+1 Link to closures question:stackoverflow.com/questions/428617/closures-in-net Article with explanation of compiler generated code blogs.msdn.com/b/abhinaba/archive/2005/10/18/482180.aspx

2018年10月21日35分22秒

Nice; but I'd use Include instead of Append since Append implies an order which the values may not have.

2018年10月21日35分22秒

devstuff - that is a good point, I didn't really ever think about it from that perspective.

2018年10月22日35分22秒

HBoss: I'm gonna use that. It will make it so much easier to implement Flags the way we should be.

2018年10月22日35分22秒

Just figured something awesome out: All those "object" casts are causing a lot of boxing. If you add a generic constraint of where T : struct (so that T can't be a reference type), you can actually cast (int)(ValueType)value and avoid the boxing: I've edited the answer to show this.

2018年10月22日35分22秒

But the values have to be discreet. So no floats or doubles etc. Just for completeness' sake ;)

2018年10月21日35分22秒

Why would you want to be able to assign just any old value to an enum? Isn't the point of an enum to limit the choices of values?

2018年10月21日35分22秒

I believe the compiler has to support this for the sake of supporting flags. So given the enum above, if you do MyEnum val = MyEnum.Val1 | MyEnum.Val2 you would end up with a value that is outside of the already defined possible values. (in this case 3). Since you can do binary arithmetic on enums they can theoretically have many possible values.

2018年10月21日35分22秒

One good reason would be to match it to the ID column of a read-only bootstrap table in a database.

2018年10月21日35分22秒

You can also have [Flags] to tell that the enum is flag based

2018年10月21日35分22秒