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!.
We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.
Some of us even mastered the stuff like Genericsanonymous typeslambdas,LINQ, ...
But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?

Keywords

yield by Michael Stum
var by Michael Stum
using() statement by kokos
readonly by kokos
as by Mike Stone
as / is by Ed Swangren
as / is (improved) by Rocketpants
default by deathofrats
global:: by pzycoman
using() blocks by AlexCuse
volatile by Jakub Šturc
extern alias by Jakub Šturc

Attributes

Syntax

?? (coalesce nulls) operator by kokos
number flaggings by Nick Berardi
where T:new by 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
enum values by lfoust
@variablenames by marxidad
event operators by marxidad
format string brackets by Portman
property accessor accessibility modifiers by xanadont
conditional (ternary) operator (?:) by JasonS
checked and unchecked operators by Binoj Antony
implicit and explicit operators by Flory

Language Features

Nullable types by Brad Barker
Currying by Brian Leahy
anonymous types by Keith
__makeref __reftype __refvalue by Judah Himango
object initializers by lomaxx
format strings by David in Dakota
Extension Methods by marxidad
partial methods by Jon Erickson
preprocessor directives by John Asbeck
DEBUG pre-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 roosteronacid

Visual Studio Features

select block of text in editor by Himadri
snippets by DannySmurf

Framework

TransactionScope by KiwiBastard
DependantTransaction by KiwiBastard
Nullable by IainMH
Mutex by Diago
System.IO.Path by ageektrapped
WeakReference by Juan Manuel

Methods and Properties

String.IsNullOrEmpty() method by KiwiBastard
List.ForEach() method by KiwiBastard
BeginInvoke()EndInvoke() methods by Will Dean
Nullable.HasValue and Nullable.Value properties by Rismo
GetValueOrDefault method by John Sheehan

Tips & 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 roosteronacid

Other

This came to my mind after I learned the following from this question:
where T : struct
We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.
Some of us even mastered the stuff like Genericsanonymous typeslambdas,LINQ, ...
But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?

Keywords

yield by Michael Stum
var by Michael Stum
using() statement by kokos
readonly by kokos
as by Mike Stone
as / is by Ed Swangren
as / is (improved) by Rocketpants
default by deathofrats
global:: by pzycoman
using() blocks by AlexCuse
volatile by Jakub Šturc
extern alias by Jakub Šturc

Attributes

Syntax

?? (coalesce nulls) operator by kokos
number flaggings by Nick Berardi
where T:new by 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
enum values by lfoust
@variablenames by marxidad
event operators by marxidad
format string brackets by Portman
property accessor accessibility modifiers by xanadont
conditional (ternary) operator (?:) by JasonS
checked and unchecked operators by Binoj Antony
implicit and explicit operators by Flory

Language Features

Nullable types by Brad Barker
Currying by Brian Leahy
anonymous types by Keith
__makeref __reftype __refvalue by Judah Himango
object initializers by lomaxx
format strings by David in Dakota
Extension Methods by marxidad
partial methods by Jon Erickson
preprocessor directives by John Asbeck
DEBUG pre-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 roosteronacid

Visual Studio Features

select block of text in editor by Himadri
snippets by DannySmurf

Framework

TransactionScope by KiwiBastard
DependantTransaction by KiwiBastard
Nullable by IainMH
Mutex by Diago
System.IO.Path by ageektrapped
WeakReference by Juan Manuel

Methods and Properties

String.IsNullOrEmpty() method by KiwiBastard
List.ForEach() method by KiwiBastard
BeginInvoke()EndInvoke() methods by Will Dean
Nullable.HasValue and Nullable.Value properties by Rismo
GetValueOrDefault method by John Sheehan

Tips & 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 roosteronacid

Other

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 implement IDAL: create 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:
IDAL GetDAL(); // 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:
Tuple tup = 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 Tuple Create(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 Create
The full code looks something like this:
public abstract class Tuple
{
    public static Tuple Create(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 : struct
We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.
Some of us even mastered the stuff like Genericsanonymous typeslambdas,LINQ, ...
But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?

Keywords

yield by Michael Stum
var by Michael Stum
using() statement by kokos
readonly by kokos
as by Mike Stone
as / is by Ed Swangren
as / is (improved) by Rocketpants
default by deathofrats
global:: by pzycoman
using() blocks by AlexCuse
volatile by Jakub Šturc
extern alias by Jakub Šturc

Attributes

Syntax

?? (coalesce nulls) operator by kokos
number flaggings by Nick Berardi
where T:new by 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
enum values by lfoust
@variablenames by marxidad
event operators by marxidad
format string brackets by Portman
property accessor accessibility modifiers by xanadont
conditional (ternary) operator (?:) by JasonS
checked and unchecked operators by Binoj Antony
implicit and explicit operators by Flory

Language Features

Nullable types by Brad Barker
Currying by Brian Leahy
anonymous types by Keith
__makeref __reftype __refvalue by Judah Himango
object initializers by lomaxx
format strings by David in Dakota
Extension Methods by marxidad
partial methods by Jon Erickson
preprocessor directives by John Asbeck
DEBUG pre-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 roosteronacid

Visual Studio Features

select block of text in editor by Himadri
snippets by DannySmurf

Framework

TransactionScope by KiwiBastard
DependantTransaction by KiwiBastard
Nullable by IainMH
Mutex by Diago
System.IO.Path by ageektrapped
WeakReference by Juan Manuel

Methods and Properties

String.IsNullOrEmpty() method by KiwiBastard
List.ForEach() method by KiwiBastard
BeginInvoke()EndInvoke() methods by Will Dean
Nullable.HasValue and Nullable.Value properties by Rismo
GetValueOrDefault method by John Sheehan

Tips & 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 roosteronacid

Other

No comments: