We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?Keywords
yieldby Michael Stum
varby Michael Stum
using()statement by kokos
readonlyby kokos
asby Mike Stone
as/isby Ed Swangren
as/is(improved) by Rocketpants
defaultby deathofrats
global::by pzycoman
using()blocks by AlexCuse
volatileby Jakub Šturc
extern aliasby Jakub ŠturcAttributes
DefaultValueAttributeby Michael Stum
ObsoleteAttributeby DannySmurf
DebuggerDisplayAttributeby Stu
DebuggerBrowsableandDebuggerStepThroughby bdukes
ThreadStaticAttributeby marxidad
FlagsAttributeby Martin Clarke
ConditionalAttributeby AndrewBurnsSyntax
??(coalesce nulls) operator by kokos
number flaggings by Nick Berardi
where T:newby Lars Mæhlum
implicit generics by Keith
one-parameter lambdas by Keith
auto properties by Keith
namespace aliases by Keith
verbatim string literals with @ by Patrick
enumvalues by lfoust
@variablenames by marxidad
eventoperators by marxidad
format string brackets by Portman
property accessor accessibility modifiers by xanadont
conditional (ternary) operator (?:) by JasonS
checkedanduncheckedoperators by Binoj Antony
implicit and explicitoperators by FloryLanguage Features
Nullable types by Brad Barker
Currying by Brian Leahy
anonymous types by Keith
__makeref __reftype __refvalueby Judah Himango
object initializers by lomaxx
format strings by David in Dakota
Extension Methods by marxidad
partialmethods by Jon Erickson
preprocessor directives by John Asbeck
DEBUGpre-processor directive by Robert Durgin
operator overloading by SefBkn
type inferrence by chakrit
boolean operators taken to next level by Rob Gough
pass value-type variable as interface without boxing by Roman Boiko
programmatically determine declared variable type by Roman Boiko
Static Constructors by Chris
Easier-on-the-eyes / condensed ORM-mapping using LINQ by roosteronacidVisual Studio Features
Framework
TransactionScopeby KiwiBastard
DependantTransactionby KiwiBastard
Nullableby IainMH
Mutexby Diago
System.IO.Pathby ageektrapped
WeakReferenceby Juan ManuelMethods and Properties
String.IsNullOrEmpty()method by KiwiBastard
List.ForEach()method by KiwiBastard
BeginInvoke(),EndInvoke()methods by Will Dean
Nullableand.HasValue Nullableproperties by Rismo.Value
GetValueOrDefaultmethod by John SheehanTips & Tricks
nice method for event handlers by Andreas H.R. Nilsson
uppercase comparisons by John
access anonymous types without reflection by dp
a quick way to lazily instantiate collection properties by Will
JavaScript-like anonymous inline-functions by roosteronacidOther
This came to my mind after I learned the following from this question:where T : structWe, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?Keywords
yieldby Michael Stum
varby Michael Stum
using()statement by kokos
readonlyby kokos
asby Mike Stone
as/isby Ed Swangren
as/is(improved) by Rocketpants
defaultby deathofrats
global::by pzycoman
using()blocks by AlexCuse
volatileby Jakub Šturc
extern aliasby Jakub ŠturcAttributes
DefaultValueAttributeby Michael Stum
ObsoleteAttributeby DannySmurf
DebuggerDisplayAttributeby Stu
DebuggerBrowsableandDebuggerStepThroughby bdukes
ThreadStaticAttributeby marxidad
FlagsAttributeby Martin Clarke
ConditionalAttributeby AndrewBurnsSyntax
??(coalesce nulls) operator by kokos
number flaggings by Nick Berardi
where T:newby Lars Mæhlum
implicit generics by Keith
one-parameter lambdas by Keith
auto properties by Keith
namespace aliases by Keith
verbatim string literals with @ by Patrick
enumvalues by lfoust
@variablenames by marxidad
eventoperators by marxidad
format string brackets by Portman
property accessor accessibility modifiers by xanadont
conditional (ternary) operator (?:) by JasonS
checkedanduncheckedoperators by Binoj Antony
implicit and explicitoperators by FloryLanguage Features
Nullable types by Brad Barker
Currying by Brian Leahy
anonymous types by Keith
__makeref __reftype __refvalueby Judah Himango
object initializers by lomaxx
format strings by David in Dakota
Extension Methods by marxidad
partialmethods by Jon Erickson
preprocessor directives by John Asbeck
DEBUGpre-processor directive by Robert Durgin
operator overloading by SefBkn
type inferrence by chakrit
boolean operators taken to next level by Rob Gough
pass value-type variable as interface without boxing by Roman Boiko
programmatically determine declared variable type by Roman Boiko
Static Constructors by Chris
Easier-on-the-eyes / condensed ORM-mapping using LINQ by roosteronacidVisual Studio Features
Framework
TransactionScopeby KiwiBastard
DependantTransactionby KiwiBastard
Nullableby IainMH
Mutexby Diago
System.IO.Pathby ageektrapped
WeakReferenceby Juan ManuelMethods and Properties
String.IsNullOrEmpty()method by KiwiBastard
List.ForEach()method by KiwiBastard
BeginInvoke(),EndInvoke()methods by Will Dean
Nullableand.HasValue Nullableproperties by Rismo.Value
GetValueOrDefaultmethod by John SheehanTips & Tricks
nice method for event handlers by Andreas H.R. Nilsson
uppercase comparisons by John
access anonymous types without reflection by dp
a quick way to lazily instantiate collection properties by Will
JavaScript-like anonymous inline-functions by roosteronacidOther
RealProxy lets you create your own proxies for existing types.This is super-advanced and I haven't seen anyone else use it -- which may mean that it's also really not that useful for most folks -- but it's one of those things that's good to know.Basically, the .NET RealProxy class lets you create what is called a transparent proxy to another type. Transparent in this case means that it looks completely like the proxied target object to its client -- but it's really not: it's an instance of your class, which is derived from RealProxy.This lets you apply powerful and comprehensive interception and "intermediation" services between the client and any methods or properties invoked on the real target object. Couple this power with the factory pattern (IoC etc), and you can hand back transparent proxies instead of real objects, allowing you to intercept all calls to the real objects and perform actions before and after each method invocation. In fact, I believe this is the very functionality .NET uses for remoting across app domain, process, and machine boundaries: .NET intercepts all access, sends serialized info to the remote object, receives the response, and returns it to your code.Maybe an example will make it clear how this can be useful: I created a reference service stack for my last job as enterprise architect which specified the standard internal composition (the "stack") of any new WCF services across the division. The model mandated that the data access layer for (say) the Foo service implementIDALcreate a Foo, read a Foo, update a Foo, delete a Foo. Service developers used supplied common code (from me) that would locate and load the required DAL for a service:: IDALGetDAL (); // retrieve data access layer for entity T Data access strategies in that company had often been, well, performance-challenged. As an architect, I couldn't watch over every service developer to make sure that he/she wrote a performant data access layer. But what I could do within the GetDAL factory pattern was create a transparent proxy to the requested DAL (once the common service model code located the DLL and loaded it), and use high-performance timing APIs to profile all calls to any method of the DAL. Ranking laggards then is just a matter of sorting DAL call timings by descending total time. The advantage to this over development profiling (e.g. in the IDE) is that it can be done in the production environment as well, to ensure SLAs.Here is an example of test code I wrote for the "entity profiler," which was common code to create a profiling proxy for any type with a single line:[Test, Category("ProfileEntity")] public void MyTest() { // this is the object that we want profiled. // we would normally pass this around and call // methods on this instance. DALToBeProfiled dal = new DALToBeProfiled(); // To profile, instead we obtain our proxy // and pass it around instead. DALToBeProfiled dalProxy = (DALToBeProfiled)EntityProfiler.Instance(dal); // or... DALToBeProfiled dalProxy2 = EntityProfiler.Instance(dal); // Now use proxy wherever we would have used the original... // All methods' timings are automatically recorded // with a high-resolution timer DoStuffToThisObject(dalProxy); // Output profiling results ProfileManager.Instance.ToConsole(); } Again, this lets you intercept all methods and properties called by the client on the target object! In your RealProxy-derived class, you have to override Invoke:[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)] // per FxCop public override IMessage Invoke(IMessage msg) { IMethodCallMessage msgMethodCall = msg as IMethodCallMessage; Debug.Assert(msgMethodCall != null); // should not be null - research Invoke if this trips. KWB 2009.05.28 // The MethodCallMessageWrapper // provides read/write access to the method // call arguments. MethodCallMessageWrapper mc = new MethodCallMessageWrapper(msgMethodCall); // This is the reflected method base of the called method. MethodInfo mi = (MethodInfo)mc.MethodBase; IMessage retval = null; // Pass the call to the method and get our return value string profileName = ProfileClassName + "." + mi.Name; using (ProfileManager.Start(profileName)) { IMessage myReturnMessage = RemotingServices.ExecuteMessage(_target, msgMethodCall); retval = myReturnMessage; } return retval; }Isn't it fascinating what .NET can do? The only restriction is that the target typemust be derived from MarshalByRefObject. I hope this is helpful to someone.I don't know if this has been posted already (I scanned the first post, couldn't find it).This is best shown with an example, assuming you have this class (to simulate a tuple), in in an attempt to demonstrate all the language features that make this possible I will go through it step by step.public class Tuple: Tuple { public readonly V1 v1; public readonly V2 v2; public Tuple(V1 v1, V2 v2) { this.v1 = v1; this.v2 = v2; } } Everyone knows how to create an instance of it, such as:Tupletup = new Tuple (1, "Hello, World!"); Not exactly rocket science, now we can of course change the type declaration of the variable to var, like this:var tup = new Tuple(1, "Hello, World!"); Still well known, to digress a bit here's a static method with type parameters, which everyone should be familiar with:public static void Create() { // stuff } Calling it is, again common knowledge, done like this:Create(); What most people don't know is that if the arguments to the generic method contains all the types it requires they can be inferred, for example:public static void Create(T1 a, T2 b) { // stuff } These two calls are identical:Create(1.0f, "test"); Create(1.0f, "test"); Since T1 and T2 is inferred from the arguments you passed. Combining this knowledge with the var keyword, we can by adding a second static class with a static method, such as:public abstract class Tuple { public static TupleCreate (V1 v1, V2 v2) { return new Tuple (v1, v2); } } Achieve this effect:var tup = Tuple.Create(1, "Hello, World!");This means that the types of the: variable "tup", the type-parameters of "Create" and the return value of "Create" are all inferred from the types you pass as arguments to CreateThe full code looks something like this:public abstract class Tuple { public static TupleCreate (V1 v1, V2 v2) { return new Tuple (v1, v2); } } public class Tuple : Tuple { public readonly V1 v1; public readonly V2 v2; public Tuple(V1 v1, V2 v2) { this.v1 = v1; this.v2 = v2; } } // Example usage: var tup = Tuple.Create(1, "test"); Which gives you fully type inferred factory methods everywhere!This came to my mind after I learned the following from this question:where T : structWe, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?Keywords
yieldby Michael Stum
varby Michael Stum
using()statement by kokos
readonlyby kokos
asby Mike Stone
as/isby Ed Swangren
as/is(improved) by Rocketpants
defaultby deathofrats
global::by pzycoman
using()blocks by AlexCuse
volatileby Jakub Šturc
extern aliasby Jakub ŠturcAttributes
DefaultValueAttributeby Michael Stum
ObsoleteAttributeby DannySmurf
DebuggerDisplayAttributeby Stu
DebuggerBrowsableandDebuggerStepThroughby bdukes
ThreadStaticAttributeby marxidad
FlagsAttributeby Martin Clarke
ConditionalAttributeby AndrewBurnsSyntax
??(coalesce nulls) operator by kokos
number flaggings by Nick Berardi
where T:newby Lars Mæhlum
implicit generics by Keith
one-parameter lambdas by Keith
auto properties by Keith
namespace aliases by Keith
verbatim string literals with @ by Patrick
enumvalues by lfoust
@variablenames by marxidad
eventoperators by marxidad
format string brackets by Portman
property accessor accessibility modifiers by xanadont
conditional (ternary) operator (?:) by JasonS
checkedanduncheckedoperators by Binoj Antony
implicit and explicitoperators by FloryLanguage Features
Nullable types by Brad Barker
Currying by Brian Leahy
anonymous types by Keith
__makeref __reftype __refvalueby Judah Himango
object initializers by lomaxx
format strings by David in Dakota
Extension Methods by marxidad
partialmethods by Jon Erickson
preprocessor directives by John Asbeck
DEBUGpre-processor directive by Robert Durgin
operator overloading by SefBkn
type inferrence by chakrit
boolean operators taken to next level by Rob Gough
pass value-type variable as interface without boxing by Roman Boiko
programmatically determine declared variable type by Roman Boiko
Static Constructors by Chris
Easier-on-the-eyes / condensed ORM-mapping using LINQ by roosteronacidVisual Studio Features
Framework
TransactionScopeby KiwiBastard
DependantTransactionby KiwiBastard
Nullableby IainMH
Mutexby Diago
System.IO.Pathby ageektrapped
WeakReferenceby Juan ManuelMethods and Properties
String.IsNullOrEmpty()method by KiwiBastard
List.ForEach()method by KiwiBastard
BeginInvoke(),EndInvoke()methods by Will Dean
Nullableand.HasValue Nullableproperties by Rismo.Value
GetValueOrDefaultmethod by John SheehanTips & Tricks
nice method for event handlers by Andreas H.R. Nilsson
uppercase comparisons by John
access anonymous types without reflection by dp
a quick way to lazily instantiate collection properties by Will
JavaScript-like anonymous inline-functions by roosteronacidOther
Thursday, September 19, 2013
tips and tricks - Hidden Features of C#? - Stack Overflow
Here's a copy of the whole first page! Read all of it!.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment