Hidden Features of C#? [closed]

2018-12-31 01:48发布

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 Generics, anonymous types, lambdas, LINQ, ...

But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?

Here are the revealed features so far:


Keywords

Attributes

Syntax

Language Features

Visual Studio Features

Framework

Methods and Properties

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

30条回答
后来的你喜欢了谁
2楼-- · 2018-12-31 02:14

The @ tells the compiler to ignore any escape characters in a string.

Just wanted to clarify this one... it doesn't tell it to ignore the escape characters, it actually tells the compiler to interpret the string as a literal.

If you have

string s = @"cat
             dog
             fish"

it will actually print out as (note that it even includes the whitespace used for indentation):

cat
             dog
             fish
查看更多
一个人的天荒地老
3楼-- · 2018-12-31 02:14

Using @ for variable names that are keywords.

var @object = new object();
var @string = "";
var @if = IpsoFacto(); 
查看更多
冷夜・残月
4楼-- · 2018-12-31 02:15

Returning anonymous types from a method and accessing members without reflection.

// Useful? probably not.
private void foo()
{
    var user = AnonCast(GetUserTuple(), new { Name = default(string), Badges = default(int) });
    Console.WriteLine("Name: {0} Badges: {1}", user.Name, user.Badges);
}

object GetUserTuple()
{
    return new { Name = "dp", Badges = 5 };
}    

// Using the magic of Type Inference...
static T AnonCast<T>(object obj, T t)
{
   return (T) obj;
}
查看更多
永恒的永恒
5楼-- · 2018-12-31 02:16

The 'default' keyword in generic types:

T t = default(T);

results in a 'null' if T is a reference type, and 0 if it is an int, false if it is a boolean, etcetera.

查看更多
还给你的自由
6楼-- · 2018-12-31 02:16

If you're trying to use curly brackets inside a String.Format expression...

int foo = 3;
string bar = "blind mice";
String.Format("{{I am in brackets!}} {0} {1}", foo, bar);
//Outputs "{I am in brackets!} 3 blind mice"
查看更多
宁负流年不负卿
7楼-- · 2018-12-31 02:18

Aliased generics:

using ASimpleName = Dictionary<string, Dictionary<string, List<string>>>;

It allows you to use ASimpleName, instead of Dictionary<string, Dictionary<string, List<string>>>.

Use it when you would use the same generic big long complex thing in a lot of places.

查看更多
登录 后发表回答