This came to my mind after I learned the following from this question [1]:
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 [2], anonymous types [3], lambdas [4], LINQ [5], ...
But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?
yield
[6] by
Michael Stum
[7]var
by
Michael Stum
[8]using()
statement by
kokos
[9]readonly
by
kokos
[10]as
by
Mike Stone
[11]as
/ is
by
Ed Swangren
[12]as
/ is
(improved) by
Rocketpants
[13]default
by
deathofrats
[14]global::
by
pzycoman
[15]using()
blocks by
AlexCuse
[16]volatile
by
Jakub Šturc
[17]extern alias
by
Jakub Šturc
[18]
DefaultValueAttribute
[19] by
Michael Stum
[20]
ObsoleteAttribute
[21] by
DannySmurf
[22]
DebuggerDisplayAttribute
[23] by
Stu
[24]
DebuggerBrowsable
[25] and
DebuggerStepThrough
[26] by
bdukes
[27]
ThreadStaticAttribute
[28] by
marxidad
[29]
FlagsAttribute
[30] by
Martin Clarke
[31]
ConditionalAttribute
[32] by
AndrewBurns
[33]
??
[34] (coalesce nulls) operator by
kokos
[35]where T:new
by
Lars Mæhlum
[37]enum
values by
lfoust
[43]event
operators by
marxidad
[45]?:
) by
JasonS
[48]checked
and unchecked
operators by
Binoj Antony
[49]implicit and explicit
operators by
Flory
[50]__makeref __reftype __refvalue
by
Judah Himango
[53]partial
methods by
Jon Erickson
[57]DEBUG
pre-processor directive by
Robert Durgin
[59]__arglist
by
Zac Bowling
[68]TransactionScope
by
KiwiBastard
[71]DependantTransaction
by
KiwiBastard
[72]Nullable<T>
by
IainMH
[73]Mutex
by
Diago
[74]System.IO.Path
by
ageektrapped
[75]WeakReference
by
Juan Manuel
[76]String.IsNullOrEmpty()
method by
KiwiBastard
[77]List.ForEach()
method by
KiwiBastard
[78]BeginInvoke()
, EndInvoke()
methods by
Will Dean
[79]Nullable<T>.HasValue
and Nullable<T>.Value
properties by
Rismo
[80]GetValueOrDefault
method by
John Sheehan
[81]This isn't C# per se, but I haven't seen anyone who really uses System.IO.Path.Combine()
to the extent that they should. In fact, the whole Path class is really useful, but no one uses it!
I'm willing to bet that every production app has the following code, even though it shouldn't:
string path = dir + "\\" + fileName;
lambdas and type inference are underrated. Lambdas can have multiple statements and they double as a compatible delegate object automatically (just make sure the signature match) as in:
Console.CancelKeyPress +=
(sender, e) => {
Console.WriteLine("CTRL+C detected!\n");
e.Cancel = true;
};
Note that I don't have a new CancellationEventHandler
nor do I have to specify types of sender
and e
, they're inferable from the event. Which is why this is less cumbersome to writing the whole delegate (blah blah)
which also requires you to specify types of parameters.
Lambdas don't need to return anything and type inference is extremely powerful in context like this.
And BTW, you can always return Lambdas that make Lambdas in the functional programming sense. For example, here's a lambda that makes a lambda that handles a Button.Click event:
Func<int, int, EventHandler> makeHandler =
(dx, dy) => (sender, e) => {
var btn = (Button) sender;
btn.Top += dy;
btn.Left += dx;
};
btnUp.Click += makeHandler(0, -1);
btnDown.Click += makeHandler(0, 1);
btnLeft.Click += makeHandler(-1, 0);
btnRight.Click += makeHandler(1, 0);
Note the chaining: (dx, dy) => (sender, e) =>
Now that's why I'm happy to have taken the functional programming class :-)
Other than the pointers in C, I think it's the other fundamental thing you should learn :-)
From Rick Strahl [1]:
You can chain the ?? operator so that you can do a bunch of null comparisons.
string result = value1 ?? value2 ?? value3 ?? String.Empty;
[1] http://www.west-wind.com/weblog/posts/236298.aspxAliased 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.
From CLR via C# [1]:
When normalizing strings, it is highly recommended that you use ToUpperInvariant instead of ToLowerInvariant because Microsoft has optimized the code for performing uppercase comparisons.
I remember one time my coworker always changed strings to uppercase before comparing. I've always wondered why he does that because I feel it's more "natural" to convert to lowercase first. After reading the book now I know why.
[1] https://rads.stackoverflow.com/amzn/click/com/0735621632My favorite trick is using the null coalesce operator [1] and parentheses to automagically instantiate collections for me.
private IList<Foo> _foo;
public IList<Foo> ListOfFoo
{ get { return _foo ?? (_foo = new List<Foo>()); } }
[1] http://en.wikipedia.org/wiki/%3F%3F_OperatorListOfFoo
influences the internal state of your class. User A of your API, who calls ListOfFoo
before FunctionThatDoesSomethingWithFoo
, might see a different behaviour than User B, who calls FunctionThatDoesSomethingWithFoo
without calling ListOfFoo
first. - jan
readonly
initialization, unless the list needs to be lazy-loaded. - Isabelle Wedin
Avoid checking for null event handlers
Adding an empty delegate to events at declaration, suppressing the need to always check the event for null before calling it is awesome. Example:
public delegate void MyClickHandler(object sender, string myValue);
public event MyClickHandler Click = delegate {}; // add empty delegate!
Let you do this
public void DoSomething()
{
Click(this, "foo");
}
Instead of this
public void DoSomething()
{
// Unnecessary!
MyClickHandler click = Click;
if (click != null) // Unnecessary!
{
click(this, "foo");
}
}
Please also see this related discussion [1] and this blog post [2] by Eric Lippert on this topic (and possible downsides).
[1] https://stackoverflow.com/questions/840715/the-proper-way-of-raising-events-in-the-net-frameworkpublic event MyClickHandler Click = (a, b) => { };
- Justin Morgan
Everything else, plus
1) implicit generics (why only on methods and not on classes?)
void GenericMethod<T>( T input ) { ... }
//Infer type, so
GenericMethod<int>(23); //You don't need the <>.
GenericMethod(23); //Is enough.
2) simple lambdas with one parameter:
x => x.ToString() //simplify so many calls
3) anonymous types and initialisers:
//Duck-typed: works with any .Add method.
var colours = new Dictionary<string, string> {
{ "red", "#ff0000" },
{ "green", "#00ff00" },
{ "blue", "#0000ff" }
};
int[] arrayOfInt = { 1, 2, 3, 4, 5 };
Another one:
4) Auto properties can have different scopes:
public int MyId { get; private set; }
Thanks @pzycoman for reminding me:
5) Namespace aliases (not that you're likely to need this particular distinction):
using web = System.Web.UI.WebControls;
using win = System.Windows.Forms;
web::Control aWebControl = new web::Control();
win::Control aFormControl = new win::Control();
for
loop in that case - the foreach
would be slower and more confusing. The Enumerable.Range
is most useful for initialising collections without a countered loop. If you're going to loop anyway it's best to stick with for
- Keith
new web.Control()
would also work in this example. The ::
syntax forces it to treat the prefix as a namespace alias, so you could have a class called web
and the web::Control
syntax would still work, while the web.Control
syntax wouldn't know whether to check the class or the namespace. Because of that I tend to always use ::
when doing namespace aliases. - Keith
(x) =>
becomes x =>
- Keith
void Add(...)
- that includes your own classes without the need to implement an interface. I agree that on the int[]
it's C# syntax, but that it works for any type with an Add method is duck-typing - Keith
System.Collections.IEnumerable
. You can get really crazy with void Add
overload: new MyClass { 1, "a", { 1, "a" } };
. See this question - HuBeZa
Add
on its own could mean something else, so List<int> x = new List<int>{1, 2, 3, 4, 5 }
should collection initialise and makes sense. However int
has an Add
method but int x = new int{1, 2, 3, 4, 5}
makes no sense. - Keith
byte[] get_bytes(){return {};}
!!! - lmat - Reinstate Monica
{
syntax for add doesn't work when the collection is empty. - Keith
I didn't know the "as" keyword for quite a while.
MyClass myObject = (MyClass) obj;
vs
MyClass myObject = obj as MyClass;
The second will return null if obj isn't a MyClass, rather than throw a class cast exception.
Two things I like are Automatic properties so you can collapse your code down even further:
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
becomes
public string Name { get; set;}
Also object initializers:
Employee emp = new Employee();
emp.Name = "John Smith";
emp.StartDate = DateTime.Now();
becomes
Employee emp = new Employee {Name="John Smith", StartDate=DateTime.Now()}
[DefaultValue()]
in stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035 ( msdn.microsoft.com/en-us/library/… ) - ANeves
DefaultValue
attribute! - Funka
[DefaultValue]
is used for the designer so it knows whether to show a property in bold (meaning non-default). - Roger Lipscombe
Option
type (in C#). Obviously Option types should initialize to None (the whole point is that they should be non-nullable). My base class constructor inspected the object for Option type properties and initialized them all to None. - Scott Whitlock
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.
Attributes in general, but most of all DebuggerDisplay [1]. Saves you years.
[1] http://msdn.microsoft.com/en-us/library/x810d419.aspxThe @ 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
{{
to {
and }}
to }
making it useful for string.Format()
. - Ferruccio
I think one of the most under-appreciated and lesser-known features of C# (.NET 3.5) are Expression Trees [1], especially when combined with Generics and Lambdas. This is an approach to API creation that newer libraries like NInject and Moq are using.
For example, let's say that I want to register a method with an API and that API needs to get the method name
Given this class:
public class MyClass
{
public void SomeMethod() { /* Do Something */ }
}
Before, it was very common to see developers do this with strings and types (or something else largely string-based):
RegisterMethod(typeof(MyClass), "SomeMethod");
Well, that sucks because of the lack of strong-typing. What if I rename "SomeMethod"? Now, in 3.5 however, I can do this in a strongly-typed fashion:
RegisterMethod<MyClass>(cl => cl.SomeMethod());
In which the RegisterMethod class uses Expression<Action<T>>
like this:
void RegisterMethod<T>(Expression<Action<T>> action) where T : class
{
var expression = (action.Body as MethodCallExpression);
if (expression != null)
{
// TODO: Register method
Console.WriteLine(expression.Method.Name);
}
}
This is one big reason that I'm in love with Lambdas and Expression Trees right now.
[1] http://msdn.microsoft.com/en-us/library/bb397951.aspxEditValue(someEmployee, e => e.FirstName);
in my business logic and have it automatically generate all the plumbing logic for a ViewModel and View to edit that property (so, a label with the text "First Name" and a TextBox with a binding that calls the setter of the FirstName property when the user edits the name, and updates the View using the getter). This seems to be the basis for most of the new internal DSLs in C#. - Scott Whitlock
" yield [1]" would come to my mind. Some of the attributes like [DefaultValue()] [2] are also among my favorites.
The " var [3]" keyword is a bit more known, but that you can use it in .NET 2.0 applications as well (as long as you use the .NET 3.5 compiler [4] and set it to output 2.0 code) does not seem to be known very well.
Edit: kokos, thanks for pointing out the ?? operator, that's indeed really useful. Since it's a bit hard to google for it (as ?? is just ignored), here is the MSDN documentation page for that operator: ?? Operator (C# Reference) [5]
[1] http://msdn.microsoft.com/en-us/library/9k7k7cf0(VS.80).aspxI tend to find that most C# developers don't know about 'nullable' types. Basically, primitives that can have a null value.
double? num1 = null;
double num2 = num1 ?? -100;
Set a nullable double, num1, to null, then set a regular double, num2, to num1 or -100 if num1 was null.
http://msdn.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx
one more thing about Nullable type:
DateTime? tmp = new DateTime();
tmp = null;
return tmp.ToString();
it is return String.Empty. Check this [1] link for more details
[1] https://stackoverflow.com/questions/4547112/is-nullable-datetime-work-correctas
operators) with generics alone. Nullable<T> alone is rudimentary and far from stellar, but the concept of nullable types as part of the language is kick ass. - P Daddy
tmp.ToString()
returns empty string because it returns "the text representation of the value of the current System.Nullable<T> object if the System.Nullable<T>.HasValue property is true, or an empty string ("") if the System.Nullable<T>.HasValue property is false." - VoodooChild
Here are some interesting hidden C# features, in the form of undocumented C# keywords:
__makeref
__reftype
__refvalue
__arglist
These are undocumented C# keywords (even Visual Studio recognizes them!) that were added to for a more efficient boxing/unboxing prior to generics. They work in coordination with the System.TypedReference struct.
There's also __arglist, which is used for variable length parameter lists.
One thing folks don't know much about is System.WeakReference [1] -- a very useful class that keeps track of an object but still allows the garbage collector to collect it.
The most useful "hidden" feature would be the yield return keyword. It's not really hidden, but a lot of folks don't know about it. LINQ is built atop this; it allows for delay-executed queries by generating a state machine under the hood. Raymond Chen recently posted about the internal, gritty details [2].
[1] http://msdn.microsoft.com/en-us/library/ms404247.aspxUnions (the C++ shared memory kind) in pure, safe C#
Without resorting to unsafe mode and pointers, you can have class members share memory space in a class/struct. Given the following class:
[StructLayout(LayoutKind.Explicit)]
public class A
{
[FieldOffset(0)]
public byte One;
[FieldOffset(1)]
public byte Two;
[FieldOffset(2)]
public byte Three;
[FieldOffset(3)]
public byte Four;
[FieldOffset(0)]
public int Int32;
}
You can modify the values of the byte fields by manipulating the Int32 field and vice-versa. For example, this program:
static void Main(string[] args)
{
A a = new A { Int32 = int.MaxValue };
Console.WriteLine(a.Int32);
Console.WriteLine("{0:X} {1:X} {2:X} {3:X}", a.One, a.Two, a.Three, a.Four);
a.Four = 0;
a.Three = 0;
Console.WriteLine(a.Int32);
}
Outputs this:
2147483647
FF FF FF 7F
65535
just add using System.Runtime.InteropServices;
Using @ for variable names that are keywords.
var @object = new object();
var @string = "";
var @if = IpsoFacto();
Class @class
is better than Class clazz
- Rob Fonseca-Ensor
@return
for the return variable, @default
for a default value, @this
for the first parameter of an extension method, etc. When I use them like this I think it really helps the clarity of the code - especially for extension methods. - Enigmativity
Event
is a valid identifier without an @
. But you do need an @
for @event
. - Mark Cidade
var
which will only be used to automatically infer the type if a type named var
doesn't exist. - Mark Cidade
@
sigil is to mitigate conflicts between languages. The ::
operator is used to differentiate identical names for classes from different assemblies. - Mark Cidade
If you want to exit your program without calling any finally blocks or finalizers use FailFast [1]:
Environment.FailFast()
[1] http://msdn.microsoft.com/en-us/library/ms131100.aspxReturning 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;
}
dynamic
keyword. If you're going to play with fire, you might was well do it the easy way. ;-) - StriplingWarrior
dynamic user = GetUserTuple();
and the rest would stay the same...) - kloffy
dynamic
doesn't replace anonymous types: it replaces the need for this AnonCast method in order to access members without reflection. - StriplingWarrior
dynamic
version is to be preferred (maybe it should be added to this answer as an alternative)... - kloffy
Here's a useful one for regular expressions and file paths:
"c:\\program files\\oldway"
@"c:\program file\newway"
The @ tells the compiler to ignore any escape characters in a string.
Mixins. Basically, if you want to add a feature to several classes, but cannot use one base class for all of them, get each class to implement an interface (with no members). Then, write an extension method for the interface, i.e.
public static DeepCopy(this IPrototype p) { ... }
Of course, some clarity is sacrificed. But it works!
Not sure why anyone would ever want to use Nullable<bool> though. :-)
True, False, FileNotFound [1]?
[1] http://thedailywtf.com/Articles/What_Is_Truth_0x3f_.aspxNullable< bool >
is to accurately answer questions like, "Have you stopped beating your wife?". Yes, No or N/A - Dan
This one is not "hidden" so much as it is misnamed.
A lot of attention is paid to the algorithms "map", "reduce", and "filter". What most people don't realize is that .NET 3.5 added all three of these algorithms, but it gave them very SQL-ish names, based on the fact that they're part of LINQ.
"map" => Select
Transforms data from one form into another"reduce" => Aggregate
Aggregates values into a single result"filter" => Where
Filters data based on a criteria
The ability to use LINQ to do inline work on collections that used to take iteration and conditionals can be incredibly valuable. It's worth learning how all the LINQ extension methods can help make your code much more compact and maintainable.
string[] fileNames = a_directoryInfo.GetFiles().Select(fileInfo => fileInfo.Name).ToArray();
- Chuck Savage
Environment.NewLine
for system independent newlines.
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"
[
and ]
are square brackets, and <
and >
are angle brackets. See en.wikipedia.org/wiki/Bracket. - icktoofay
using
block has the syntax using(expr)block
which means, that you don't have to store the IDisposable resource in a local variable. You can abuse this feature to enforce arbitrary methods to be called at the end of the block: using(Writer.Indent()) Writer.WriteLine("x");
- Christian Klauser
@Ed, I'm a bit reticent about posting this as it's little more than nitpicking. However, I would point out that in your code sample:
MyClass c;
if (obj is MyClass)
c = obj as MyClass
If you're going to use 'is', why follow it up with a safe cast using 'as'? If you've ascertained that obj is indeed MyClass, a bog-standard cast:
c = (MyClass)obj
...is never going to fail.
Similarly, you could just say:
MyClass c = obj as MyClass;
if(c != null)
{
...
}
I don't know enough about .NET's innards to be sure, but my instincts tell me that this would cut a maximum of two type casts operations down to a maximum of one. It's hardly likely to break the processing bank either way; personally, I think the latter form looks cleaner too.
is
and as
won't do user casts. So, the above code is asking with the is
operator if obj is derived from MyClass (or has an implicit system defined cast). Also, is
fails on null
. Both of these edge cases may be important to your code. For instance, you may want to write: if( obj == null || obj is MyClass ) c = (MyClass)obj;
But this is strictly different from: try { c = (MyClass)obj; } catch { }
since the former will not perform any user defined conversions, but the latter will. Without the null
check, the former will also not set c
when obj
is null
. - Adam Luter
if( obj == null || obj is MyClass ) c = (MyClass)obj;
you might as well just use as
, since it's clearer, has slightly better performance characteristics, and (if I'm reading it correctly) performs the same work. I believe it's FxCop that points out that is
performs an as
-like cast under the covers, and it flags that double-cast–style as bad practice. - Isabelle Wedin
override Equals(object arg){ try{ return ((MyClass)arg).Id == this.Id; } catch{ return base.Equals(arg); }}
- Chuck Savage
IEnumerable<int>
to List<int>
, and casting object
(new object()
) to IEnumerable<int>
, to make sure there are no mistakes: direct cast: 5.43ns, is->as cast: 6.75ns, as cast: 5.69ns. Then testing invalid casts: direct cast: 3125000ns, as cast: 5.41ns. Conclusion: stop worrying about the 1% factor, and just make sure you use is/as when the cast might be invalid, cause exceptions (also if handled) are VERY slow compared to casting, we're talking about a factor 578000 slower. Remember that last part, the rest doesn't matter (.Net FW 4.0, release build) - Aidiakapi
Maybe not an advanced technique, but one I see all the time that drives me crazy:
if (x == 1)
{
x = 2;
}
else
{
x = 3;
}
can be condensed to:
x = (x==1) ? 2 : 3;
(t == null) ? "Null" : t.GetType().Name
contains statement in the 3rd part. - Roman Boiko
Many people don't realize that they can compare strings using: OrdinalIgnoreCase instead of having to do someString.ToUpper(). This removes the additional string allocation overhead.
if( myString.ToUpper() == theirString.ToUpper() ){ ... }
becomes
if( myString.Equals( theirString, StringComparison.OrdinalIgnoreCase ) ){ ... }
Just learned, anonymous types can infer property names from the variable name:
string hello = "world";
var o = new { hello };
Console.WriteLine(o.hello);
I like looking up stuff in a list like:-
bool basketContainsFruit(string fruit) {
return new[] { "apple", "orange", "banana", "pear" }.Contains(fruit);
}
Rather than:-
bool basketContainsFruit(string fruit) {
return fruit == "apple" || fruit == "orange" || fruit == "banana" ||
fruit == "pear";
}
Doesn't come up that much in practice, but the idea of matching items against the subject of the search can be really quite useful + succinct.
switch(fruit){ case "apple": case "orange": case "banana": case "pear": return true; default: return false; }
- P Daddy
Honestly the experts by the very definition should know this stuff. But to answer your question: Built-In Types Table (C# Reference) [1]
The compiler flagging for numbers are widely known for these:
Decimal = M
Float = F
Double = D
// for example
double d = 30D;
However these are more obscure:
Long = L
Unsigned Long = UL
Unsigned Int = U
[1] http://msdn.microsoft.com/en-us/library/ya5y69ds.aspxInternalsVisibleTo [1] attribute is one that is not that well known, but can come in increadibly handy in certain circumstances. It basically allows another assembly to be able to access "internal" elements of the defining assembly.
[1] http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspxHere is a new method of the string class in C# 4.0:
String.IsNullOrWhiteSpace(String value)
It's about time.
(myString ?? "").Trim() == ""
- user47322
SomeString.AsNullIfEmpty() ?? "default value"
. - patridge
??
operator, though. - patridge
I picked this one up when using ReSharper [1]:
Implicit Method Group Conversion
//If given this:
var myStrings = new List<string>(){"abc","def","xyz"};
//Then this:
myStrings.ForEach(s => Console.WriteLine(s));
//Is equivalent to this:
myStrings.ForEach(Console.WriteLine);
See " Implicit Method Group Conversion in C# [2]" for more.
[1] http://www.jetbrains.com/resharper/There are more, but that is the three obvious ones of the top of my head...
[1] http://msdn.microsoft.com/en-us/library/system.transactions.dependenttransaction.aspxWhen debugging, you can type $exception
in the Watch\QuickWatch\Immediate window and get all the info on the exception of the current frame. This is very useful if you've got 1st chance exceptions turned on!
Dictionary.TryGetValue(K key, out V value)
Works as a check and a get in one. Rather than;
if(dictionary.ContainsKey(key))
{
value = dictionary[key];
...
}
you can just do;
if(dictionary.TryGetValue(key, out value))
{ ... }
and the value has been set.
Conditional string.Format [1]:
Applies different formatting to a number depending on whether the number is positive, negative, or zero.
string s = string.Format("{0:positive;negative;zero}", i);
e.g.
string format = "000;-#;(0)";
string pos = 1.ToString(format); // 001
string neg = (-1).ToString(format); // -1
string zer = 0.ToString(format); // (0)
[1] http://msdn.microsoft.com/en-us/library/0c899ak8.aspx#SectionSeparatorEvents are really delegates under the hood and any delegate object can have multiple functions attached to it and detatched from it using the += and -= operators, respectively.
Events can also be controlled with the add/remove, similar to get/set except they're invoked when += and -= are used:
public event EventHandler SelectiveEvent(object sender, EventArgs args)
{ add
{ if (value.Target == null) throw new Exception("No static handlers!");
_SelectiveEvent += value;
}
remove
{ _SelectiveEvent -= value;
}
} EventHandler _SelectiveEvent;
I couldn't see this looking above - one that I didn't realise you could do until recently is to call one constructor from another:
class Example
{
public Example(int value1)
: this(value1, "Default Value")
{
}
public Example(int value1, string value2)
{
m_Value1 = value1;
m_value2 = value2;
}
int m_Value1;
string m_value2;
}
More of a runtime feature, but I recently learned that there are two garbage collectors. The workstation gc and the server gc. Workstation is the default on client versions of windows, but server is much faster on multicore machines.
<configuration>
<runtime>
<gcServer enabled="true"/>
</runtime>
</configuration>
Be careful. The server gc requires more memory.
Other underused operators are checked
and unchecked
:
short x = 32767; // 32767 is the max value for short
short y = 32767;
int z1 = checked((short)(x + y)); //will throw an OverflowException
int z2 = unchecked((short)(x + y)); // will return -2
int z3 = (short)(x + y); // will return -2
short.MaxValue
? - Clinton Pierce
Use "throw;" instead of "throw ex;" to preserve stack trace
If re-throwing an exception without adding additional information, use "throw" instead of "throw ex". An empty "throw" statement in a catch block will emit specific IL that re-throws the exception while preserving the original stack trace. "throw ex" loses the stack trace to the original source of the exception.
A few hidden features I've come across:
stackalloc
which lets you allocate arrays on the stack==
and !=
operators can be overloaded to return types other than bool
. Strange but true.stackalloc
requires unsafe context. - RickNZ
I just wanted to copy that code without the comments. So, the trick is to simply press the Alt button, and then highlight the rectangle you like.(e. g. below).
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//if (e.CommandName == "sel")
//{
// lblCat.Text = e.CommandArgument.ToString();
//}
}
In the above code if I want to select :
e.CommandName == "sel"
lblCat.Text = e.Comman
Then I press ALt key and select the rectangle and no need to uncomment the lines.
Check this out.
@David in Dakota:
Console.WriteLine( "-".PadRight( 21, '-' ) );
I used to do this, until I discovered that the String class has a constructor that allows you to do the same thing in a cleaner way:
new String('-',22);
The volatile [1] keyword to tell the compiler that a field can be modified by multiple threads concurrently.
[1] http://msdn.microsoft.com/en-us/library/x13ttww7.aspxThe params keyword, i.e.
public void DoSomething(params string[] theStrings)
{
foreach(string s in theStrings)
{
// Something with the Strings…
}
}
Called like
DoSomething(“The”, “cat”, “sat”, “on”, “the” ,”mat”);
Foreach uses Duck Typing
Paraphrasing, or shamelessly stealing from Krzysztof Cwalinas blog [1] on this. More interesting trivia than anything.
For your object to support foreach, you don't have to implement IEnumerable. I.e. this is not a constraint and it isn't checked by the compiler. What's checked is that
For example,
class Foo
{
public Bar GetEnumerator() { return new Bar(); }
public struct Bar
{
public bool MoveNext()
{
return false;
}
public object Current
{
get { return null; }
}
}
}
// the following complies just fine:
Foo f = new Foo();
foreach (object o in f)
{
Console.WriteLine("Krzysztof Cwalina's da man!");
}
[1] http://blogs.msdn.com/kcwalina/archive/2007/07/18/DuckNotation.aspxAdd(x)
method. public class MyList{ public void Add(string s){} }
. You can then do var l = new MyList{"a", "b", "c"};
... - John Gibb
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." - Gabe
A couple of things I like:
-If you create an interface similar to
public interface SomeObject<T> where T : SomeObject<T>, new()
you force anything that inherits from this interface to contain a parameterless constructor. It is very useful for a couple of things I've run across.
-Using anonymous types to create a useful object on the fly:
var myAwesomeObject = new {Name="Foo", Size=10};
-Finally, many Java developers are familiar with syntax like:
public synchronized void MySynchronizedMethod(){}
However, in C# this is not valid syntax. The workaround is a method attribute:
[MethodImpl(MethodImplOptions.Synchronized)]
public void MySynchronizedMethod(){}
Static constructors.
Instances:
public class Example
{
static Example()
{
// Code to execute during type initialization
}
public Example()
{
// Code to execute during object initialization
}
}
Static classes:
public static class Example
{
static Example()
{
// Code to execute during type initialization
}
}
MSDN says [1]:
A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
For example:
public class MyWebService
{
public static DateTime StartTime;
static MyWebService()
{
MyWebService.StartTime = DateTime.Now;
}
public TimeSpan Uptime
{
get { return DateTime.Now - MyWebService.StartTime; }
}
}
But, you could also just as easily have done:
public class MyWebService
{
public static DateTime StartTime = DateTime.Now;
public TimeSpan Uptime
{
get { return DateTime.Now - MyWebService.StartTime; }
}
}
So you'll be hard-pressed to find any instance when you actually need to use a static constructor.
MSDN offers useful notes on static constructors:
A static constructor does not take access modifiers or have parameters.
A static constructor is called automatically to initialize the class before the first instance is created
or any static members are referenced.A static constructor cannot be called directly.
The user has no control on when the static constructor is executed in the program.
A typical use of static constructors is when the class is using a log file and the constructor is used to write
entries to this file.Static constructors are also useful when creating wrapper classes for
unmanaged code, when the constructor
can call the LoadLibrary method.If a static constructor throws an exception, the runtime will not
invoke it a second time, and the type will remain uninitialized for the
lifetime of the application domain in which your program is running.
The most important note is that if an error occurs in the static constructor, a TypeIntializationException
is thrown and you cannot drill down to the offending line of code. Instead, you have to examine the TypeInitializationException
's InnerException
member, which is the specific cause.
A couple other attributes from the System.Diagnostics [1] namespace are quite helpful.
DebuggerBrowsable [2] will let you hide variables from the debugger window (we use it for all private backing variables of exposed properties). Along with that, DebuggerStepThrough [3] makes the debugger step over that code, very useful for dumb properties (probably should be converted to auto-properties if you can take a dependency to the C# 3.0 compiler). As an example
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string nickName;
public string NickName {
[DebuggerStepThrough]
get { return nickName; }
[DebuggerStepThrough]
set { this.nickName = value; }
}
[1] http://msdn.microsoft.com/en-us/library/system.diagnostics.aspx[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). - Chuck Savage
C# + CLR:
Thread.MemoryBarrier
: Most people wouldn't have used it and there is some inaccurate information on MSDN. But if you know
intricacies
[1] then you can do nifty lock-free synchronization.
volatile, Thread.VolatileRead, Thread.VolatileWrite
: There are very very few people who gets the use of these and even fewer who understands all the risks they avoid and introduce :).
ThreadStatic
variables: There was only one situation in past few years I've found that ThreadStatic variables were absolutely god send and indispensable. When you want to do something for entire call chain, for example, they are very useful.
fixed
keyword: It's a hidden weapon when you want to make access to elements of large array almost as fast as C++ (by default C# enforces bound checks that slows down things).
default(typeName)
keyword can be used outside of generic class as well. It's useful to create empty copy of struct.
One of the handy feature I use is DataRow[columnName].ToString()
always returns non-null value. If value in database was NULL, you get empty string.
Use Debugger object to break automatically when you want developer's attention even if s/he hasn't enabled automatic break on exception:
#if DEBUG
if (Debugger.IsAttached)
Debugger.Break();
#endif
using ComplicatedDictionary = Dictionary<int, Dictionary<string, object>>;
ComplicatedDictionary myDictionary = new ComplicatedDictionary();
[1] http://www.albahari.com/threading/part4.aspxSince anonymous delegates were added to 2.0, we have been able to develop closures. They are rarely used by programmers but provide great benefits such as immediate code reuse. Consider this piece of code:
bool changed = false;
if (model.Prop1 != prop1)
{
changed = true;
model.Prop1 = prop1;
}
if (model.Prop2 != prop2)
{
changed = true;
model.Prop2 = prop2;
}
// ... etc.
Note that the if-statements above perform similar pieces of code with the exception of one line of code, i.e. setting different properties. This can be shortened with the following, where the varying line of code is entered as a parameter to an Action
object, appropriately named setAndTagChanged
:
bool changed = false;
Action<Action> setAndTagChanged = (action) =>
{
changed = true;
action();
};
if (model.Prop1 != prop1) setAndTagChanged(() => model.Prop1 = prop1);
if (model.Prop2 != prop2) setAndTagChanged(() => model.Prop2 = prop2);
In the second case, the closure allows you to scope the change
variable in your lambda, which is a concise way to approach this problem.
An alternate way is to use another unused feature, the "or equal" binary assignment operator. The following code shows how:
private bool conditionalSet(bool condition, Action action)
{
if (condition) action();
return condition;
}
// ...
bool changed = false;
changed |= conditionalSet(model.Prop1 == prop1, () => model.Prop1 = prop1);
changed |= conditionalSet(model.Prop2 == prop2, () => model.Prop2 = prop2);
I'd say using certain system classes for extension methods is very handy, for example System.Enum, you can do something like below...
[Flags]
public enum ErrorTypes : int {
None = 0,
MissingPassword = 1,
MissingUsername = 2,
PasswordIncorrect = 4
}
public static class EnumExtensions {
public static T Append<T> (this System.Enum type, T value) where T : struct
{
return (T)(ValueType)(((int)(ValueType) type | (int)(ValueType) value));
}
public static T Remove<T> (this System.Enum type, T value) where T : struct
{
return (T)(ValueType)(((int)(ValueType)type & ~(int)(ValueType)value));
}
public static bool Has<T> (this System.Enum type, T value) where T : struct
{
return (((int)(ValueType)type & (int)(ValueType)value) == (int)(ValueType)value);
}
}
...
//used like the following...
ErrorTypes error = ErrorTypes.None;
error = error.Append(ErrorTypes.MissingUsername);
error = error.Append(ErrorTypes.MissingPassword);
error = error.Remove(ErrorTypes.MissingUsername);
//then you can check using other methods
if (error.Has(ErrorTypes.MissingUsername)) {
...
}
This is just an example of course - the methods could use a little more work...
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. - John Gibb
Being able to have enum types have values other than int (the default)
public enum MyEnum : long
{
Val1 = 1,
Val2 = 2
}
Also, the fact that you can assign any numeric value to that enum:
MyEnum e = (MyEnum)123;
MyEnum e = (MyEnum)123;
, but when you access e you'll get an Exception. - ANeves
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<Foo>:
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<T> GetDAL<T>(); // 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<DALToBeProfiled>.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 type must be derived from MarshalByRefObject. I hope this is helpful to someone.
I just found out about this one today -- and I've been working with C# for 5 years!
It's the namespace alias qualifier [1]:
extern alias YourAliasHere;
You can use it to load multiple versions of the same type. This can be useful in maintenance or upgrade scenarios where you have an updated version of your type that won't work in some old code, but you need to upgrade it to the new version. Slap on a namespace alias qualifier [2], and the compiler will let you have both types in your code.
[1] http://msdn.microsoft.com/en-us/library/ms173212(VS.80).aspx
{ anywhere inside members }, { using only braces }, { with no control statement }.
void MyWritingMethod() {
int sameAge = 35;
{ // scope some work
string name = "Joe";
Log.Write(name + sameAge.ToString());
}
{ // scope some other work
string name = "Susan";
Log.Write(name + sameAge.ToString());
}
// I'll never mix up Joe and Susan again
}
Inside large, confusing or archaic members (not that they should ever exist, however,) it helps me prevent against using wrong variable names. Scope stuff to finer levels.
For example, this XML writing code follows the indentation level of the actual generated XML (i.e. Visual Studio will indent the scoping braces accordingly)
XmlWriter xw = new XmlWriter(..);
//<root>
xw.WriteStartElement("root");
{
//<game>
xw.WriteStartElement("game");
{
//<score>#</score>
for (int i = 0; i < scores.Length; ++i) // multiple scores
xw.WriteElementString("score", scores[i].ToString());
}
//</game>
xw.WriteEndElement();
}
//</root>
xw.WriteEndElement();
(Also another use to keep temp work out of the main scope)
Provided by
Patrik
[1]: sometimes used to mimic the VB "with-statement" in C#.
var somePerson = this.GetPerson(); // whatever
{
var p = somePerson;
p.FirstName = "John";
p.LastName = "Doe";
//...
p.City = "Gotham";
}
For the discerning programmer.
[1] https://stackoverflow.com/users/46187/Debug.Indent()
and a Debug.Unindent()
. Gives a good visual in the code of what's happening. - Ryan Lundy
Not hidden, but I think that a lot of developers are not using the HasValue and Value properties on the nullable types.
int? x = null;
int y;
if (x.HasValue)
y = x.Value;
x != null
over x.HasValue
. - ANeves
y = x.Value
and y = (int)x
? - Justin Morgan
Nullable<int>
with a value will be boxed as an int
, but a Nullable<int>
without a value will actually be boxed as a null
. If you wrote your own Nullable class, it would be boxed as a YourNullable<int>
either way, and a comparison with null would NEVER be equal (since there actually IS a boxed value on the heap). - John Gibb
My favourite is the
global::
keyword to escape namespace hell with some of our 3rd party code providers...
Example:
global::System.Collections.Generic.List<global::System.String> myList =
new global::System.Collections.Generic.List<global::System.String>();
global
when used with the namespace alias qualifier ::
refers to the global namespace, which is the default namespace for any C# program. Example usage here - msdn.microsoft.com/en-us/library/c3ay4x3d.aspx - Robin Maben
I've read through all seven pages, and I'm missing these:
String.Join
I've seen a lot of for-loops to convert a list of items to a string with separators. It's always a pain to make sure you doin't start with a separator and don't end with a separator. A built-in method makes this easier:
String.Join(",", new String[] { "a", "b", "c"});
TODO in comment
Not really a C# feature, more of a Visual Studio feature. When you start your comment with TODO, it's added to your Visual Studio Task List (View -> Task List. Comments)
// TODO: Implement this!
throw new NotImplementedException();
Extension methods meets Generics
You can combine extension methods with Generics, when you think of the tip earlier in this topic, you can add extensions to specific interfaces
public static void Process<T>(this T item) where T:ITest,ITest2 {}
Enumerable.Range
Just want a list of integers?
Enumerable.Range(0, 15)
I'll try to think of some more...
String.Join
and Enumerable.Range
remind me of Python's equivalents: ",".join(["a", "b", "c"])
and range(0, 15)
. - Ray
Enumerable.Range
can be used as an alternative to a for
loop. Instead of doing this for(i = 0; i < 15; i++)
, you can do this foreach (int i in Enumerable.Range(0, 15))
. - Ray
You can "use" multiple objects in one using statement.
using (Font f1= new Font("Arial", 10.0f), f2 = new Font("Arial", 10.0f))
{
// Use f1 and f2.
}
Note that there is already an answer stating that you can do this:
using (Font f1= new Font("Arial", 10.0f))
using (Font f2 = new Font("Arial", 10.0f))
{ }
Which is different from mine.
Width in string.Format()
Console.WriteLine("Product: {0,-7} Price: {1,5}", product1, price1);
Console.WriteLine("Product: {0,-7} Price: {1,5}", product2, price2);
produces
from Prabir's Blog | Hidden C# feature [1]
[1] http://blog.prabir.me/post/Hidden-C-feature-stringFormat-Width.aspxtypedefs
Someone posted that they miss typedefs but you can do it like this
using ListOfDictionary = System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, string>>;
and declare it as
ListOfDictionary list = new ListOfDictionary();
I like the keyword continue.
If you hit a condition in a loop and don't want to do anything but advance the loop just stick in "continue;".
E.g.:
foreach(object o in ACollection)
{
if(NotInterested)
continue;
}
Two of my personal favourites, which I see rarely used:
@lomaxx I also learned the other day (the same time I learned your tip) is that you can now have disparate access levels on the same property:
public string Name { get; private set;}
That way only the class itself can set the Name property.
public MyClass(string name) { Name = name; }
Nesting Using Statements
Usually we do it like this:
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter()) {
using (IndentedTextWriter itw = new IndentedTextWriter(sw)) {
...
}
}
But we can do it this way:
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter())
using (IndentedTextWriter itw = new IndentedTextWriter(sw)) {
...
}
JavaScript-like anonymous inline-functions
Return a String:
var s = new Func<String>(() =>
{
return "Hello World!";
})();
Return a more complex Object:
var d = new Func<Dictionary<Int32, String>>(() =>
{
return new Dictionary<Int32, String>
{
{ 0, "Foo" },
{ 1, "Bar" },
{ 2, "..." }
};
})();
A real-world use-case:
var tr = new TableRow();
tr.Cells.AddRange
(
new[]
{
new TableCell { Text = "" },
new TableCell { Text = "" },
new TableCell { Text = "" },
new TableCell
{
Text = new Func<String>(() =>
{
return @"Result of a chunk of logic, without having to define
the logic outside of the TableCell constructor";
})()
},
new TableCell { Text = "" },
new TableCell { Text = "" }
}
);
Note: You cannot re-use variable names inside the inline-function's scope.
Alternative syntax
// The one-liner
Func<Int32, Int32, String> Add = (a, b) => Convert.ToString(a + b);
// Multiple lines
Func<Int32, Int32, String> Add = (a, b) =>
{
var i = a + b;
return i.ToString();
};
// Without parameters
Func<String> Foo = () => "";
// Without parameters, multiple lines
Func<String> Foo = () =>
{
return "";
};
Shorten a string and add horizontal ellipsis...
Func<String, String> Shorten = s => s.Length > 100 ? s.Substring(0, 100) + "…" : s;
There's also the ThreadStaticAttribute to make a static field unique per thread, so you can have strongly typed thread-local storage.
Even if extension methods aren't that secret (LINQ is based on them), it may not be so obvious as to how useful and more readable they can be for utility helper methods:
//for adding multiple elements to a collection that doesn't have AddRange
//e.g., collection.Add(item1, item2, itemN);
static void Add<T>(this ICollection<T> coll, params T[] items)
{ foreach (var item in items) coll.Add(item);
}
//like string.Format() but with custom string representation of arguments
//e.g., "{0} {1} {2}".Format<Custom>(c=>c.Name,"string",new object(),new Custom())
// result: "string {System.Object} Custom1Name"
static string Format<T>(this string format, Func<T,object> select, params object[] args)
{ for(int i=0; i < args.Length; ++i)
{ var x = args[i] as T;
if (x != null) args[i] = select(x);
}
return string.Format(format, args);
}
Full access to the call stack:
public static void Main()
{
StackTrace stackTrace = new StackTrace(); // get call stack
StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
// write call stack method names
foreach (StackFrame stackFrame in stackFrames)
{
Console.WriteLine(stackFrame.GetMethod().Name); // write method name
}
}
So, if you'll take the first one - you know what function you are in. If you're creating a helper tracing function - take one before the last one - you'll know your caller.
On-demand field initialization in one line:
public StringBuilder Builder
{
get { return _builder ?? (_builder = new StringBuilder()); }
}
I'm not sure how I feel about C# supporting assignment expressions, but hey, it's there :-)
Easily determine type with which variable was declared (from my answer [1]):
using System;
using System.Collections.Generic;
static class Program
{
public static Type GetDeclaredType<T>(T x)
{
return typeof(T);
}
// Demonstrate how GetDeclaredType works
static void Main(string[] args)
{
IList<string> iList = new List<string>();
List<string> list = null;
Console.WriteLine(GetDeclaredType(iList).Name);
Console.WriteLine(GetDeclaredType(list).Name);
}
}
Results:
IList`1
List`1
And its name (borrowed from "Get variable name" [2]):
static void Main(string[] args)
{
Console.WriteLine("Name is '{0}'", GetName(new {args}));
Console.ReadLine();
}
static string GetName<T>(T item) where T : class
{
var properties = typeof(T).GetProperties();
return properties[0].Name;
}
Result: Name is 'args'
Console.WriteLine(iList.GetType().Name);
? - user34537
List'1
as the first result, not IList'1
. And null-reference exception instead of the second result. GetType()
returns type of an object, not declared type of variable. - Roman Boiko
new {args}
. They are available since C# 3.0, and this code can be built for .NET 2.0 using C# 3.0 compiler. About anonymous types see also csharpindepth.com/Articles/General/BluffersGuide3.aspx - Roman Boiko
It's not actually a C# hidden feature, but I recently discovered the WeakReference class [1] and was blown away by it (although this may be biased by the fact that it helped me found a solution to a particular problem of mine [2]...)
[1] http://msdn.microsoft.com/en-us/library/system.weakreference.aspxThe Environment.UserInteractive [1] property.
[1] http://msdn.microsoft.com/en-us/library/system.environment.userinteractive.aspxThe UserInteractive property reports false for a Windows process or a service like IIS that runs without a user interface. If this property is false, do not display modal dialogs or message boxes because there is no graphical user interface for the user to interact with.
Programmers moving from C/C++ may miss this one:
In C#, % (modulus operator) works on floats!
AppDomain.UnhandledException Event [1] is also candidate for being hidden.
This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application. If sufficient information about the state of the application is available, other actions may be undertaken — such as saving program data for later recovery. Caution is advised, because program data can become corrupted when exceptions are not handled.
We can see, even on this site, a lot of people are wondering why their application is not starting, why it crashed, etc. The AppDomain.UnhandledException
event can be very useful for such cases as it provides the possibility at least to log the reason of application failure.
The C# ?? null coalescing operator -
Not really hidden, but rarely used. Probably because a lot of developers run a mile when they see the conditional ? operator, so they run two when they see this one. Used:
string mystring = foo ?? "foo was null"
rather than
string mystring;
if (foo==null)
mystring = "foo was null";
else
mystring = foo;
?
the traditional way as mystring = foo.IsNullOrEmpty() ? "foo was null" : foo;
since the time I first read about ternary operators and thought I was so cool! Until, now.. :P - Robin Maben
The #if DEBUG pre-processor directive. It is Useful for testing and debugging (though I usually prefer to go the unit testing route).
string customerName = null;
#if DEBUG
customerName = "Bob"
#endif
It will only execute code block if Visual Studio is set to compile in 'Debug' mode. Otherwise the code block will be ignored by the compiler (and grayed out in Visual Studio).
I didn't find anyone who is using string.Join to join strings using a separator. Everyone keeps writing the same ugly for-loop
var sb = new StringBuilder();
var count = list.Count();
for(int i = 0; i < count; i++)
{
if (sb.Length > 0) sb.Append(seperator);
sb.Append(list[i]);
}
return sb.ToString();
instead of
return string.Join(separator, list.ToArray());
if (sb.Length > 0) sb.Append(seperator);
to remove the preceding separator. You also want to cache any Count()
functions to save re-evaluations and string.Join()
is only for arrays. Like many others devs I have my own extension methods which is cleaner that string.Join()
- mythz
Charlie Calvert explains partial methods on his blog [1]
Scott Cate has a nice partial method demo here [2]
true [1] and false [2] operators are really weird.
More comprehensive example can be found here [3].
Edit: There is related SO question What’s the false operator in C# good for? [4]
[1] http://msdn.microsoft.com/en-us/library/6x6y6z4d.aspxclass MyClass { public static bool operator true(MyClass o) { return o != null; } public static bool operator false(MyClass o) { return o == null; } public static bool operator !(MyClass o) { return o ? false : true; } }
- HuBeZa
There are some really hidden keywords and features in C# related to the TypedReference undocumented class. The following keywords are undocumented:
__makeref
__reftype
__refvalue
__arglist
Examples of use:
// Create a typed reference
int i = 1;
TypedReference tr1 = __makeref(i);
// Get the type of a typed reference
Type t = __reftype(tr1);
// Get the value of a typed referece
int j = __refvalue(tr1, int);
// Create a method that accepts and arbitrary number of typed references
void SomeMethod(__arglist) { ...
// Call the method
int x = 1;
string y = "Foo";
Object o = new Object();
SomeMethod(__arglist(x,y,o));
// And finally iterate over method parameters
void SomeMethod(__arglist) {
ArgIterator ai = new ArgIterator(__arglist);
while(ai.GetRemainingCount() >0)
{
TypedReference tr = ai.GetNextArg();
Console.WriteLine(TypedReference.ToObject(tr));
}}
I found that only few developers know about this feature.
If you need a method that works with a value-type variable via some interface (implemented by this value type), it's easy to avoid boxing during the method call.
Example code:
using System;
using System.Collections;
interface IFoo {
void Foo();
}
struct MyStructure : IFoo {
public void Foo() {
}
}
public static class Program {
static void MethodDoesNotBoxArguments<T>(T t) where T : IFoo {
t.Foo();
}
static void Main(string[] args) {
MyStructure s = new MyStructure();
MethodThatDoesNotBoxArguments(s);
}
}
IL code doesn't contain any box instructions:
.method private hidebysig static void MethodDoesNotBoxArguments<(IFoo) T>(!!T t) cil managed
{
// Code size 14 (0xe)
.maxstack 8
IL_0000: ldarga.s t
IL_0002: constrained. !!T
IL_0008: callvirt instance void IFoo::Foo()
IL_000d: ret
} // end of method Program::MethodDoesNotBoxArguments
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 15 (0xf)
.maxstack 1
.locals init ([0] valuetype MyStructure s)
IL_0000: ldloca.s s
IL_0002: initobj MyStructure
IL_0008: ldloc.0
IL_0009: call void Program::MethodDoesNotBoxArguments<valuetype MyStructure>(!!0)
IL_000e: ret
} // end of method Program::Main
See Richter, J. CLR via C# [1], 2nd edition, chapter 14: Interfaces, section about Generics and Interface Constraints.
See also my answer [2] to another question.
[1] http://rads.stackoverflow.com/amzn/click/0735621632void BoxingMethod(IFoo x)
cause boxing if x
is a value type. Your example doesn't allow calls of interface methods. Code above allows such calls without boxing. - Roman Boiko
On the basis that this thread should be entitled "things you didn't know about C# until recently despite thinking you already knew everything", my personal feature is asynchronous delegates.
Until I read Jeff Richter's C#/CLR book (excellent book, everyone doing .NET should read it) I didn't know that you could call any delegate using BeginInvoke
/ EndInvoke
. I tend to do a lot of ThreadPool.QueueUserWorkItem
calls (which I guess is much like what the delegate BeginInvoke
is doing internally), but the addition of a standardised join/rendezvous pattern may be really useful sometimes.
Near all the cool ones have been mentioned. Not sure if this one's well known or not
C# property/field constructor initialization:
var foo = new Rectangle()
{
Fill = new SolidColorBrush(c),
Width = 20,
Height = 20
};
This creates the rectangle, and sets the listed properties.
I've noticed something funny - you can have a comma at the end of the properties list, without it being a syntax error. So this is also valid:
var foo = new Rectangle()
{
Fill = new SolidColorBrush(c),
Width = 20,
Height = 20,
};
Several people have mentioned using blocks, but I think they are much more useful than people have realised. Think of them as the poor man's AOP tool. I have a host of simple objects that capture state in the constructor and then restore it in the Dispose() method. That allows me to wrap a piece of functionality in a using block and be sure that the state is restored at the end. For example:
using(new CursorState(this, BusyCursor));
{
// Do stuff
}
CursorState captures the current cursor being used by form, then sets the form to use the cursor supplied. At the end it restores the original cursor. I do loads of things like this, for example capturing the selections and current row on a grid before refreshing and so on.
Another note on event handlers: you can simply create a raise extension method like so:
public static class EventExtensions {
public static void Raise<T>(this EventHandler<T> @event,
object sender, T args) where T : EventArgs {
if(@event!= null) {
@event(sender, args);
}
}
}
Then you can use it to raise events:
public class MyImportantThing {
public event EventHandler<MyImportantEventEventArgs> SomethingHappens;
...
public void Bleh() {
SomethingHappens.Raise(this, new MyImportantEventEventArgs { X=true });
}
}
This method has the added advantage of enforcing a coding standard (using EventHandler<>
).
There isn't a point in writing the same exact function over and over and over again. Perhaps the next version of C# will finally have an InlineAttribute
that can be placed on the extension method and will cause the compiler to inline the method definition (which would make this way nearly standard, and the fastest).
edit: removed temp variable inside extension method based on comments
temp
variable. It's used for avoiding an async change, but the event
parameter is sufficient for that. - jpbochi
I'm late to this party, so my first choices are already taken. But I didn't see anyone mention this gem yet:
Parallel Extensions to the .NET Framework [1]
It has things like replace with Parallel.For or foreach with Parallel.ForEach
Parallel Sample :
In your opinion, how many CLR object can be created in one second?
See fallowing example :
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace ObjectInitSpeedTest
{
class Program
{
//Note: don't forget to build it in Release mode.
static void Main()
{
normalSpeedTest();
parallelSpeedTest();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Press a key ...");
Console.ReadKey();
}
private static void parallelSpeedTest()
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("parallelSpeedTest");
long totalObjectsCreated = 0;
long totalElapsedTime = 0;
var tasks = new List<Task>();
var processorCount = Environment.ProcessorCount;
Console.WriteLine("Running on {0} cores", processorCount);
for (var t = 0; t < processorCount; t++)
{
tasks.Add(Task.Factory.StartNew(
() =>
{
const int reps = 1000000000;
var sp = Stopwatch.StartNew();
for (var j = 0; j < reps; ++j)
{
new object();
}
sp.Stop();
Interlocked.Add(ref totalObjectsCreated, reps);
Interlocked.Add(ref totalElapsedTime, sp.ElapsedMilliseconds);
}
));
}
// let's complete all the tasks
Task.WaitAll(tasks.ToArray());
Console.WriteLine("Created {0:N} objects in 1 sec\n", (totalObjectsCreated / (totalElapsedTime / processorCount)) * 1000);
}
private static void normalSpeedTest()
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("normalSpeedTest");
const int reps = 1000000000;
var sp = Stopwatch.StartNew();
sp.Start();
for (var j = 0; j < reps; ++j)
{
new object();
}
sp.Stop();
Console.WriteLine("Created {0:N} objects in 1 sec\n", (reps / sp.ElapsedMilliseconds) * 1000);
}
}
}
[1] http://msdn.microsoft.com/en-us/concurrency/default.aspxOne great class I like is System.Xml.XmlConvert
which can be used to read values from xml tag. Especially, if I am reading a boolean value from xml attribute or element, I use
bool myFlag = System.Xml.XmlConvert.ToBoolean(myAttribute.Value);
Note: since boolean type in xml accepts 1 and 0 in addition to "true" and "false" as valid values, using string comparison in this case is error-prone.
Everyone has seen one. Basically, when you see this:
[assembly: ComVisible(false)]
The "assembly:" portion of that attribute is the target. In this case, the attribute is applied to the assembly, but there are others:
[return: SomeAttr]
int Method3() { return 0; }
In this sample the attribute is applied to the return value.
[1] http://msdn.microsoft.com/en-us/library/b3787ac0.aspxApologies for posting so late, I am new to Stack Overflow so missed the earlier opportunity.
I find that EventHandler<T>
is a great feature of the framework that is underutilised.
Most C# developers I come across still define a custom event handler delegate when they are defining custom events, which is simply not necessary anymore.
Instead of:
public delegate void MyCustomEventHandler(object sender, MyCustomEventArgs e);
public class MyCustomEventClass
{
public event MyCustomEventHandler MyCustomEvent;
}
you can go:
public class MyCustomEventClass
{
public event EventHandler<MyCustomEventArgs> MyCustomEvent;
}
which is a lot more concise, plus you don't get into the dilemma of whether to put the delegate in the .cs file for the class that contains the event, or the EventArgs derived class.
What about IObservable?
Pretty much everybody knows IEnumerable [1] but their mathematical dual seems to be unknown IObservable [2]. Maybe because its new in .NET 4.
What it does is instead of pulling the information (like an enumerable) it pushes information to the subscriber(s) of the observerable.
Together with the Rx extensions [3] it will change how we deal with events. Just to illustrate how powerful it is check a very short example here [4].
[1] http://msdn.microsoft.com/en-us/library/9eekhta0.aspxOK, it may seem obvious, but I want to mention the Object.Equals
method (the static one, with two arguments).
I'm pretty sure many people don't even know about it, or forget it's there, yet it can really help in some cases. For instance, when you want to compare two objects for equality, not knowing if they're null. How many times did you write something like that :
if ((x == y) || ((x != null && y != null) && x.Equals(y)))
{
...
}
When you can just write :
if (Object.Equals(x, y))
{
...
}
(Object.Equals
is actually implemented exactly like in the first code sample)
string.Empty
I know it's not fantastical (ludicrously odd), but I use it all the time instead of "".
And it's pretty well hidden until someone tells you it's there.
string.Empty
is more 'correct'. For reference though, .Empty
isn't exactly a sparsely used value, most value types implement it, and Microsoft's guidelines encourage it's use (and indeed, static versions of common values, MinValue
and MaxValue
being two other common values). It can prevent unnecessary creation of duplicate value types when the same instance can be used (immutable value types). - Matthew Scharley
String.Empty
is much clearer. This holds for the .Empty
pattern in general: you see it in many more types. - Jeroen Wiert Pluimers
string.Empty
vs ""
- personally I find the latter much easier to read, and it makes no different to the compiled code. - Keith
typename.property
in C# - bobobobo
""
and string.Empty
will not have the same behavior during ==
comparisons. - Brian
I see a lot of people replicate the functionality of Nullable<T>.GetValueOrDefault(T)
.
C# 3.0's LINQ query comprehensions are full-blown monadic comprehensions a la Haskell (in fact they were designed by one of Haskell's designers). They will work for any generic type that follows the "LINQ pattern" and allows you to write in a pure monadic functional style, which means that all of your variables are immutable (as if the only variables you used were IDisposable
s and IEnumerable
s in using and foreach statements). This is helpful for keeping variable declarations close to where they're used and making sure that all side-effects are explicitly declared, if there are any at all.
interface IFoo<T>
{ T Bar {get;}
}
class MyFoo<T> : IFoo<T>
{ public MyFoo(T t) {Bar = t;}
public T Bar {get; private set;}
}
static class Foo
{ public static IFoo<T> ToFoo<T>(this T t) {return new MyFoo<T>(t);}
public static void Do<T>(this T t, Action<T> a) { a(t);}
public static IFoo<U> Select<T,U>(this IFoo<T> foo, Func<T,U> f)
{ return f(foo.Bar).ToFoo();
}
}
/* ... */
using (var file = File.OpenRead("objc.h"))
{ var x = from f in file.ToFoo()
let s = new Scanner(f)
let p = new Parser {scanner = s}
select p.Parse();
x.Do(p =>
{ /* drop into imperative code to handle file
in Foo monad if necessary */
});
}
Not really hidden, but useful. When you've got an enum
with flags
, you can use shift-left to make things clearer. e.g.
[Flags]
public enum ErrorTypes {
None = 0,
MissingPassword = 1 << 0,
MissingUsername = 1 << 1,
PasswordIncorrect = 1 << 2
}
0000 0001
shifted one place left is 0000 00010
which is 2. It's a nice trick but I'm not sure it's clearer than = 1, = 2, = 4 etc unless you know bit shifting. It makes sure the reader has some CS experience though :) - Chris S
1 << 9
than 512. YMMV! - Steve Dunn
My favorite attribute: InternalsVisibleTo [1]
At assembly level you can declare that another assembly can see your internals. For testing purposes this is absolutely wonderful.
Stick this in your AssemblyInfo.cs or equivalent and your test assembly get full access to all the internal stuff that requires testing.
[assembly: InternalsVisibleTo("MyLibrary.Test, PublicKey=0024...5c042cb")]
As you can see, the test assembly must have a strong name [2] to gain the trust of the assembly under test.
Available in .Net Framework 2.0+, Compact Framework 2.0+ and XNA Framework 1.0+.
[1] http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspxI love using the @ character for SQL queries. It keeps the sql nice and formatted and without having to surround each line with a string delimiter.
string sql = @"SELECT firstname, lastname, email
FROM users
WHERE username = @username AND password = @password";
The extern alias [1] keyword to reference two versions of assemblies that have the same fully-qualified type names.
[1] http://msdn.microsoft.com/en-us/library/ms173212.aspxYou can limit the life and thus scope of variables by using { }
brackets.
{
string test2 = "3";
Console.Write(test2);
}
Console.Write(test2); //compile error
test2
only lives within the brackets.
Need to return an empty IEnumerable?
public IEnumerable<T> GetEnumerator(){
yield break;
}
System.Linq.Enumerable.Empty<T>()
- chakrit
return new T[0];
. There are many ways to do this. This is but just one. But it is an interesting one... - user1228
T[]
, so new T[0]
is only called once per type. - phoog
yield break
in a generator function (i.e. which also yield return
s) I'd use Enumerable.Empty everywhere else - sehe
You can use any Unicode character in C# names, for example:
public class MyClass
{
public string Hårføner()
{
return "Yes, it works!";
}
}
You can even use Unicode escapes. This one is equivalent to the above:
public class MyClass
{
public string H\u00e5rføner()
{
return "Yes, it (still) works!";
}
}
float area = Math.π * (radius * radius)
. What I'd really like to do is define an extension method called ²
so I can type float area = Math.π * radius.²();
- MattDavey
Ability to use LINQ Expressions to perform strongly-typed reflection:
static void Main(string[] args)
{
var domain = "matrix";
Check(() => domain);
Console.ReadLine();
}
static void Check<T>(Expression<Func<T>> expr)
{
var body = ((MemberExpression)expr.Body);
Console.WriteLine("Name is: {0}", body.Member.Name);
Console.WriteLine("Value is: {0}", ((FieldInfo)body.Member)
.GetValue(((ConstantExpression)body.Expression).Value));
}
// output:
// Name is: 'domain'
// Value is: 'matrix'
More details are available at How to Find Out Variable or Parameter Name in C#? [1]
[1] http://rabdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.htmlYou can store colors in Enum.
public enum MyEnumColors : uint
{
Normal = 0xFF9F9F9F,
Active = 0xFF8EA98A,
Error = 0xFFFF0000
}
I have often come across the need to have a generic parameter-object persisted into the viewstate in a base class.
public abstract class BaseListControl<ListType,KeyType,ParameterType>
: UserControl
where ListType : BaseListType
&& ParameterType : BaseParameterType, new
{
private const string viewStateFilterKey = "FilterKey";
protected ParameterType Filters
{
get
{
if (ViewState[viewStateFilterKey] == null)
ViewState[viewStateFilterKey]= new ParameterType();
return ViewState[viewStateFilterKey] as ParameterType;
}
set
{
ViewState[viewStateFilterKey] = value;
}
}
}
Usage:
private void SomeEventHappened(object sender, EventArgs e)
{
Filters.SomeValue = SomeControl.SelectedValue;
}
private void TimeToFetchSomeData()
{
GridView.DataSource = Repository.GetList(Filters);
}
This little trick with the "where ParameterType : BaseParameterType, new" is what makes it really work.
With this property in my baseclass, I can automate handling of paging, setting filter values to filter a gridview, make sorting really easy, etc.
I am really just saying that generics can be an enormously powerful beast in the wrong hands.
How about the FlagsAttribute [1] on an enumeration? It allows you to perform bitwise operations... took me forever to find out how to do bitwise operations in .NET nicely.
[1] http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspxYou can add and remove delegates with less typing.
Usual way:
handler += new EventHandler(func);
Less typing way:
handler += func;
Using "~" operator with FlagAttribute and enum
Sometime we would use Flag attribute with enum to perform bitwise manipulation on the enumeration.
[Flags]
public enum Colors
{
None = 0,
Red = 1,
Blue = 2,
White = 4,
Black = 8,
Green = 16,
All = 31 //It seems pretty bad...
}
Notice that, the value of option "All" which in enum is quite strange.
Instead of that we can use "~" operator with flagged enum.
[Flags]
public enum Colors
{
None = 0,
Red = 1,
Blue = 2,
White = 4,
Black = 8,
Green = 16,
All = ~0 //much better now. that mean 0xffffffff in default.
}
All = Red | Blue | White | Black | Green
and e.g. Dark = Blue | Black, Light = All & ~Dark
- sehe
Also useful, but not commonly used : Constrained Execution Regions [1].
A quote from BCL Team blog :
Constrained execution regions (CER's) exist to help a developer write her code to maintain consistency. The CLR doesn't guarantee that the developer's code is correct, but the CLR does hoist all of the runtime-induced failure points (ie, async exceptions) to either before the code runs, or after it has completed. Combined with constraints on what the developer can put in a CER, these are a useful way of making strong guarantees about whether your code will execute. CER's are eagerly prepared, meaning that when we see one, we will eagerly JIT any code found in its statically-discoverable call graph. If the CLR's host cares about stack overflow, we'll probe for some amount of stack space as well (though perhaps not enough stack space for any arbitrary method*). We also delay thread aborts until the CER has finished running.
It can be useful when making edits to more than one field of a data structure in an atomic fashion. So it helps to have transactions on objects.
Also CriticalFinalizerObject [2] seems to be hidden(at least who are not writing unsafe code). A CriticalFinalizerObject guarantees that garbage collection will execute the finalizer. Upon allocation, the finalizer and its call graph are prepared in advance.
[1] http://msdn.microsoft.com/en-us/library/ms228973.aspxfixed [1] statement
This statement prevents the garbage collector from relocating a movable variable. Fixed can also be used to create fixed size buffers.
The fixed statement sets a pointer to a managed variable and "pins" that variable during the execution of statement.
stackalloc [2]
The stackalloc allocates a block of memory on the stack.
[1] http://msdn.microsoft.com/en-us/library/f58wzh21(VS.80).aspxAllows you to tell the compiler to omit the call to the method marked with the attribute under certain conditions (#define).
The fact that the method call is omitted also means that its parameters are not evaluated. This is very handy and it's what allows you to call expensive validation functions in Debug.Assert() and not worry about them slowing down your release build.
[1] http://msdn.microsoft.com/en-us/library/aa664622(VS.71).aspxOne feature that I only learned about here on Stack Overflow was the ability to set an attribute on the return parameter.
[AttributeUsage( AttributeTargets.ReturnValue )]
public class CuriosityAttribute:Attribute
{
}
public class Bar
{
[return: Curiosity]
public Bar ReturnANewBar()
{
return new Bar();
}
}
This was truly a hidden feature for me :-)
Labeling my endregions...
#region stuff1
#region stuff1a
//...
#endregion stuff1a
#endregion stuff1
When defining custom attributes you can use them with [MyAttAttribute] or with [MyAtt]. When classes exist for both writings, then a compilation error occures.
The @ special character can be used to distinguish between them:
[AttributeUsage(AttributeTargets.All)]
public class X: Attribute
{}
[AttributeUsage(AttributeTargets.All)]
public class XAttribute: Attribute
{}
[X] // Error: ambiguity
class Class1 {}
[XAttribute] // Refers to XAttribute
class Class2 {}
[@X] // Refers to X
class Class3 {}
[@XAttribute] // Refers to XAttribute
class Class4 {}
When a class implements INotifyPropertyChanged [1] and you want to inform the binding system (WPF, Silverlight, etc.) that multiple bound properties of an object (ViewModel) have changed you can raise the PropertyChanged-Event with null or String.Empty.
This is documented in MSDN, but code examples and articles often don´t explain this possibility. I found it very useful.
public class BoundObject : INotifyPropertyChanged {
private int _value;
private string _text;
public event PropertyChangedEventHandler PropertyChanged;
public int Value {
get {
return _value;
}
set {
if (_value != value) {
_value = value;
OnPropertyChanged("Value");
}
}
}
public string Text {
get {
return _text;
}
set {
if (_text != value) {
_text = value;
OnPropertyChanged("Text");
}
}
}
public void Init(){
_text = "InitialValue";
_value = 1;
OnPropertyChanged(string.Empty);
}
public void Reset() {
_text = "DefaultValue";
_value = 0;
OnPropertyChanged(string.Empty);
}
private void OnPropertyChanged(string propertyName) {
PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);
if (PropertyChanged != null) {
PropertyChanged(this, e);
}
}
}
[1] http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=VS.80%29.aspxYou can put several attributes in one pair of square brackets:
[OperationContract, ServiceKnownType(typeof(Prism)), ServiceKnownType(typeof(Cuboid))]
Shape GetShape();
Lambda Expressions
Func<int, int, int> add = (a, b) => (a + b);
Obscure String Formats
Console.WriteLine("{0:D10}", 2); // 0000000002
Dictionary<string, string> dict = new Dictionary<string, string> {
{"David", "C#"},
{"Johann", "Perl"},
{"Morgan", "Python"}
};
Console.WriteLine( "{0,10} {1, 10}", "Programmer", "Language" );
Console.WriteLine( "-".PadRight( 21, '-' ) );
foreach (string key in dict.Keys)
{
Console.WriteLine( "{0, 10} {1, 10}", key, dict[key] );
}
I didn't start to really appreciate the "using" blocks until recently. They make things so much more tidy :)
What about using this:
#if DEBUG
Console.Write("Debugging");
#else
Console.Write("Final");
#endif
When you have your solution compiled with DEBUG defined it will output "Debugging".
If your compile is set to Release it will write "Final".
FlagsAttribute, a small but nice feature [1] when using enum to make a bitmasks:
[Flags]
public enum ConfigOptions
{
None = 0,
A = 1 << 0,
B = 1 << 1,
Both = A | B
}
Console.WriteLine( ConfigOptions.A.ToString() );
Console.WriteLine( ConfigOptions.Both.ToString() );
// Will print:
// A
// A, B
[1] http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspxI'm becoming a big fan of extension methods since they can add much wanted functionality to existing code or code you can't edit. One of my favorites I add in to everything I do now is for string.IsNullOrEmpty()
public static class Strings
{
public static bool IsNullOrEmpty(this string value)
{
return string.IsNullOrEmpty(value);
}
}
This lets you shorten your code a bit like this
var input = Console.ReadLine();
if (input.IsNullOrEmpty())
{
Console.WriteLine("try again");
}
input.IsNullOrEmpty()
- Julien N
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<V1, V2> : 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<int, string> tup = new Tuple<int, string>(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<int, string>(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<T1, T2>()
{
// stuff
}
Calling it is, again common knowledge, done like this:
Create<float, double>();
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, T2>(T1 a, T2 b)
{
// stuff
}
These two calls are identical:
Create<float, string>(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<V1, V2> Create<V1, V2>(V1 v1, V2 v2)
{
return new Tuple<V1, V2>(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<V1, V2> Create<V1, V2>(V1 v1, V2 v2)
{
return new Tuple<V1, V2>(v1, v2);
}
}
public class Tuple<V1, V2> : 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!
Easier-on-the-eyes / condensed ORM-mapping using LINQ
Consider this table:
[MessageId] INT,
[MessageText] NVARCHAR(MAX)
[MessageDate] DATETIME
... And this structure:
struct Message
{
Int32 Id;
String Text;
DateTime Date;
}
Instead of doing something along the lines of:
List<Message> messages = new List<Message>();
foreach (row in DataTable.Rows)
{
var message = new Message
{
Id = Convert.ToInt32(row["MessageId"]),
Text = Convert.ToString(row["MessageText"]),
Date = Convert.ToDateTime(row["MessageDate"])
};
messages.Add(message);
}
You can use LINQ and do the same thing with fewer lines of code, and in my opinion; more style. Like so:
var messages = DataTable.AsEnumerable().Select(r => new Message
{
Id = Convert.ToInt32(r["MessageId"]),
Text = Convert.ToString(r["MessageText"]),
Date = Convert.ToDateTime(r["MessageDate"])
}).ToList();
This approach can be nested, just like loops can.
r.Field<int>("MessageId")
(I wish I didn't have to know that) - kͩeͣmͮpͥ ͩ
Falling through switch
-case
s can be achieved by having no code in a case
(see case 0
), or using the special goto case
(see case 1
) or goto default
(see case 2
) forms:
switch (/*...*/) {
case 0: // shares the exact same code as case 1
case 1:
// do something
goto case 2;
case 2:
// do something else
goto default;
default:
// do something entirely different
break;
}
Something I missed for a long time: you can compare strings with
"string".equals("String", StringComparison.InvariantCultureIgnoreCase)
instead of doing:
"string".ToLower() == "String".ToLower();
A couple I can think of:
[field: NonSerialized()]
public EventHandler event SomeEvent;
This prevents the event from being serialised. The 'field:' indicates that the attribute should be applied to the event's backing field.
Another little known feature is overriding the add/remove event handlers:
public event EventHandler SomeEvent
{
add
{
// ...
}
remove
{
// ...
}
}
I love the fact that I can use LINQ to objects on plain old .NET 2.0 (i.e. without requiring .NET 3.5 to be installed everywhere). All you need is an implementation of all the query operator Extension methods - see LINQBridge [1]
[1] http://www.albahari.com/nutshell/linqbridge.htmlI can't comment yet, but note that by default Visual Studio 2008 automatically steps over properties, so the DebuggerStepThrough attribute is no longer needed in that case.
Also, I haven't noticed anyone showing how to declare a parameter-less lambda (useful for implementing Action<>)
() => DoSomething(x);
You should also read up on closures - I'm not clever enough to explain them properly. But basically it means that the compiler does clever stuff so that the x in that line of code will still work even if it goes 'out of scope' after creating the lambda.
I also discovered recently that you can pretend to ignore a lambda parameter:
(e, _) => DoSomething(e)
It's not really ignoring it, it's just that _ is a valid identifier. So you couldn't ignore both of the parameters like that, but I think it is a kind of neat way to indicate that we don't care about that parameter (typically the EventArgs which is .Empty
).
There are operators for performing
implicit
[1] and
explicit
[2] user-defined type conversion between the declared class and one or more arbitrary classes. The implicit
operator effectively allows the simulation of overloading the assignement operator, which is possible in languages such as C++ but not C#.
It doesn't seem to be a feature one comes across very often, but it is in fact used in the
LINQ to XML
[3] (System.Xml.Linq
) library, where you can implicitly convert strings to XName
objects. Example:
XName tagName = "x:Name";
I discovered this feature in this article [4] about how to simulate multiple inheritance in C#.
[1] http://msdn.microsoft.com/en-us/library/z5z9kes2.aspxThe delegate syntax have evolved over successive versions of C#, but I still find them difficult to remember. Fortunately the Action<>
and Func<>
delegates are easy to remember.
For example:
Action<int>
is a delegate method that takes a single int argument and returns void.Func<int>
is a delegate method that takes no arguments and returns an int.Func<int, bool>
is a delegate method that takes a single int argument and returns a bool.These features were introduced in version 3.5 of the .NET framework.
You can use generics to check (compile time) if a method argument implements two interfaces:
interface IPropA
{
string PropA { get; set; }
}
interface IPropB
{
string PropB { get; set; }
}
class TestClass
{
void DoSomething<T>(T t) where T : IPropA, IPropB
{
MessageBox.Show(t.PropA);
MessageBox.Show(t.PropB);
}
}
Same with an argument that is inherited from a base class and an interface.
t
implements the given interfaces is known explicitly from the where
(in fact, that is all that is known, other than that t
is an object), so the cast is unnecessary. When t.PropA is accessed, it works exactly as if t were a non-generic parameter of type IPropA, and when t.PropB is accessed, it works exactly as if t were a non-generic parameter of type IPropB. - P Daddy
Extension methods can be called on null
; this will not cause a NullReferenceException
to be thrown.
Example application: you can define an alternative for ToString()
called ToStringOrEmpty()
which will return the empty string when called on null
.
To call the base class constructor just put base() inline with the constructor.
To call the base class method you can just put base.MethodName() inside the derived class method
class ClassA
{
public ClassA(int a)
{
//Do something
}
public void Method1()
{
//Do Something
}
}
class ClassB : ClassA
{
public ClassB(int a) : base(a) // calling the base class constructor
{
//Do something
}
public void Method2()
{
base.Method1(); // calling the base class method
}
}
Of course you can call the methods of the base class by just saying base.MethodName()
TrueForAll Method of List<T>
:
List<int> s = new List<int> { 6, 1, 2 };
bool a = s.TrueForAll(p => p > 0);
One thing not many people know about are some of the C#-introduced preprocessor directives. You can use #error This is an error.
to generate a compiler error and #warning This is a warning.
I usually use these when I'm developing with a top-down approach as a "todo" list. I'll #error Implement this function
, or #warning Eventually implement this corner case
as a reminder.
Not sure if this one got mentioned yet but the ThreadStatic attribute is a realy useful one. This makes a static field static just for the current thread.
[ThreadStatic]
private static int _ThreadStaticInteger;
You should not include an initializer because it only get executed once for the entire application, you're better off making the field nullable and checking if the value is null before you use it.
And one more thing for ASP.NET applications threads are reused so if you modify the value it could end up being used for another page request.
Still I have found this useful on several occasions. For example in creating a custom transaction class that:
using (DbTransaction tran = new DbTransaction())
{
DoQuery("...");
DoQuery("...");
}
The DbTransaction constructor sets a ThreadStatic field to its self and resets it to null in the dispose method. DoQuery checks the static field and if != null uses the current transaction if not it defaults to something else. We avoid having to pass the transaction to each method plus it makes it easy to wrap other methods that were not originaly meant to be used with transaction inside a transaction ...
Just one use :)
The Or
assignment operator is quite nice. You can write this:
x |= y
instead of this:
x = x | y
This is often practical if you have to a variable or property (x
in the example) that starts out as false
but you want to change it to the value of some other boolean variable/property only when that other value is true
.
Nested classes can access private members of a outer class.
public class Outer
{
private int Value { get; set; }
public class Inner
{
protected void ModifyOuterMember(Outer outer, int value)
{
outer.Value = value;
}
}
}
And now together with the above feature you can also inherit from nested classes as if they were top level classes as shown below.
public class Cheater : Outer.Inner
{
protected void MakeValue5(Outer outer)
{
ModifyOuterMember(outer, 5);
}
}
These features allow for some interesting possibilities as far as providing access to particular members via somewhat hidden classes.
You can change rounding scheme using:
var value = -0.5;
var value2 = 0.5;
var value3 = 1.4;
Console.WriteLine( Math.Round(value, MidpointRounding.AwayFromZero) ); //out: -1
Console.WriteLine(Math.Round(value2, MidpointRounding.AwayFromZero)); //out: 1
Console.WriteLine(Math.Round(value3, MidpointRounding.ToEven)); //out: 1
Preprocessor Directives can be nifty if you want different behavior between Debug and Release modes.
http://msdn.microsoft.com/en-us/library/ed8yd1ha.aspx
System.Diagnostics.Debug.Assert (false);
will trigger a popup and allow you to attach a debugger to a running .NET process during execution. Very useful for those times when for some reason you can't directly debug an ASP.NET application.
String interning. This is one that I haven't seen come up in this discussion yet. It's a little obscure, but in certain conditions it can be useful.
The CLR keeps a table of references to literal strings (and programmatically interned strings). If you use the same string in several places in your code it will be stored once in the table. This can ease the amount of memory required for allocating strings.
You can test if a string is interned by using String.IsInterned(string) [1] and you can intern a string using String.Intern(string) [2].
Note: The CLR can hold a reference to an interned string after application or even AppDomain end. See the MSDN documentation for details.
[1] http://msdn.microsoft.com/en-us/library/system.string.isinterned.aspxIEnumerable
's SelectMany
, which flattens a list of lists into a single list. Let's say I have a list of Orders
, and each Order
has a list of LineItems
on that order.
I want to know the total number of LineItems
sold...
int totalItems = Orders.Select(o => o.LineItems).SelectMany(i => i).Sum();
Working with enums.
Convert a string to an Enum:
enum MyEnum
{
FirstValue,
SecondValue,
ThirdValue
}
string enumValueString = "FirstValue";
MyEnum val = (MyEnum)Enum.Parse(typeof(MyEnum), enumValueString, true)
When comparing variables of type enum, you don't have to cast to int:
MyEnum val = MyEnum.SecondValue;
if (val < MyEnum.ThirdValue)
{
// Do something
}
I quite enjoy implicit generic parameters on functions. For example, if you have:
public void DoStuff<T>(T value);
Instead of calling it like this:
DoStuff<int>(5);
You can:
DoStuff(5);
And it'll work out the generic type from the parameter's type.
To test if an IEnumerable<T>
is empty with LINQ, use:
IEnumerable
<T>
.Any();
<T>
.Count() != 0)...
<T>
to be enumerated.<T>
.FirstOrDefault() == null)...
<T>
.Any() is the most succinct and performs the best.Enumerable.Count() == 0
is faster than Enumerable.Any()
in cases where the collection has been enumerated and is an IList or array. - MattDavey
I'm pretty sure everyone is familiar with operator overloading, but maybe some aren't.
class myClass
{
private string myClassValue = "";
public myClass(string myString)
{
myClassValue = myString;
}
public override string ToString()
{
return myClassValue;
}
public static myClass operator <<(myClass mc, int shiftLen)
{
string newString = "";
for (int i = shiftLen; i < mc.myClassValue.Length; i++)
newString += mc.myClassValue[i].ToString();
mc.myClassValue = newString.ToString();
return mc;
}
public static myClass operator >>(myClass mc, int shiftLen)
{
char[] newString = new char[shiftLen + mc.myClassValue.Length];
for (int i = shiftLen; i < mc.myClassValue.Length; i++)
newString[i] += mc.myClassValue[i - shiftLen];
mc.myClassValue = new string(newString);
return mc;
}
public static myClass operator +(myClass mc, string args)
{
if (args.Trim().Length > 1)
mc.myClassValue += args;
return mc;
}
public static myClass operator -(myClass mc, string args)
{
if (args.Trim().Length > 1)
{
Regex rgx = new Regex(args);
mc.myClassValue = rgx.Replace(mc.myClassValue, "");
}
return mc;
}
}
I think it's pretty cool to be able to shift a string left and right using << and >> or to remove a set of strings that follow a regular expression pattern using -=
myClass tmpClass = new myClass(" HelloWorld123");
tmpClass -= @"World";
tmpClass <<= 2;
Console.WriteLine(tmpClass);
Not a C# specific thing, but I am a ternary operations junkie.
Instead of
if (boolean Condition)
{
//Do Function
}
else
{
//Do something else
}
you can use a succinct
booleanCondtion ? true operation : false operation;
e.g.
Instead of
int value = param;
if (doubleValue)
{
value *= 2;
}
else
{
value *= 3;
}
you can type
int value = param * (tripleValue ? 3 : 2);
It does help write succinct code, but nesting the damn things can be nasty, and they can be used for evil, but I love the little suckers nonetheless
You can switch on string!
switch(name)
{
case "Dave":
return true;
case "Bob":
return false;
default:
throw new ApplicationException();
}
Very handy! and a lot cleaner than a bunch of if-else statements
Instead of doing something cheesy like this:
Console.WriteLine("{0} item(s) found.", count);
I use the following inline trick:
Console.WriteLine("{0} item{1} found.", count, count==1 ? "" : "s");
This will display "item" when there's one item or "items" when there are more (or less) than 1. Not much effort for a little bit of professionalism.
Expression to initialize a Dictionary in C# 3.5:
new Dictionary<string, Int64>() {{"Testing", 123}, {"Test", 125}};
C# allows you to add property setter methods to concrete types that implement readonly interface properties even though the interface declaration itself has no property setter. For example:
public interface IReadOnlyFoo
{
object SomeReadOnlyProperty { get; }
}
The concrete class looks like this:
internal class Foo : IReadOnlyFoo
{
public object SomeReadOnlyProperty { get; internal set; }
}
What's interesting about this is that the Foo class is immutable if you cast it to the IReadOnlyFoo interface:
// Create a Foo instance
Foo foo = new Foo();
// This statement is legal
foo.SomeReadOnlyProperty = 12345;
// Make Foo read only
IReadOnlyFoo readOnlyFoo = foo;
// This statement won't compile
readOnlyFoo.SomeReadOnlyProperty = 54321;
Foo
? - ChaosPandion
return new ReadOnlyObject(new WriteableVersion() { Property1 = value, //Set all writeable fields... });
- BenAlabaster
Dictionary initializers are always useful for quick hacks and unit tests where you need to hardcode some data.
var dict = new Dictionary<int, string> { { 10, "Hello" }, { 20, "World" } };
With LINQ it's possible to create new functions based on parameters. That's very nice if you have a tiny function which is exectued very often, but the parameters need some time to calculate.
public Func<int> RandomGenerator
{
get
{
var r = new Random();
return () => { return r.Next(); };
}
}
void SomeFunction()
{
var result1 = RandomGenerator();
var x = RandomGenerator;
var result2 = x();
}
In addition to duncansmart's reply, also extension methods can be used on Framework 2.0. Just add an ExtensionAttribute
class under System.Runtime.CompilerServices namespace and you can use extension methods (only with C# 3.0 of course).
namespace System.Runtime.CompilerServices
{
public class ExtensionAttribute : Attribute
{
}
}
You type "prop" and then press [TAB] twice, it generates useful code for your properties and can speed your typing.
I know this works in VS 2005 (I use it) but I don´t know in previous versions.
Ctrl K, Ctrl X
shows all the snippets available in Visual Studio. - Patrick
Determines whether the specified Object instances are the same instance.
Parameters:
Example:
object o = null;
object p = null;
object q = new Object();
Console.WriteLine(Object.ReferenceEquals(o, p));
p = q;
Console.WriteLine(Object.ReferenceEquals(p, q));
Console.WriteLine(Object.ReferenceEquals(o, p));
Difference to "==" and ".Equals":
Basically, Equals() tests of object A has the same content as object B.
The method System.Object.ReferenceEquals() always compares references. Although a class can provide its own behavior for the equality operator (below), that re-defined operator isn't invoked if the operator is called via a reference to System.Object.
For strings there isn't really a difference, because both == and Equals have been overriden to compare the content of the string.
See also this answer [1] to another question ("How do I check for nulls in an ‘==’ operator overload without infinite recursion?").
[1] https://stackoverflow.com/questions/73713/how-do-i-check-for-nulls-in-an-operator-overload-without-infinite-recursion#73732Explicit interface member implementation [1], wherein an interface member is implemented, but hidden unless the instance is cast to the interface type.
[1] http://msdn.microsoft.com/en-us/library/aa664591(VS.71).aspxThis isn't a C# specific type, but I just found the ISurrogateSelector and ISerializationSurrogate interfaces --
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.isurrogateselector.aspx
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.isurrogateselector.aspx
Using these in conjunction with the BinaryFormatter allows for non-serializable objects to be serialized via the implementation of a surrogate class. The surrogate pattern is well-understood in computer science, particularly when dealing with the problem of serialization. I think that this implementation is just tucked away as a parameter of the constructor to BinaryFormatter, and that's too bad.
Still - VERY hidden. :)
dynamic keyword in C# 4.0
You can use dynamic keyword, if you want your method calls to be resolved only at the runtime.
dynamic invoker=new DynamicInvoker();
dynamic result1=invoker.MyMethod1();
dynamic result2=invoker.MyMethod2();
Here I'm implementing a dynamic invoker.
public class DynamicInvoker : IDynamicObject
{
public MetaObject GetMetaObject
(System.Linq.Expressions.Expression parameter)
{
return new DynamicReaderDispatch (parameter);
}
}
public class DynamicDispatcher : MetaObject
{
public DynamicDispatcher (Expression parameter)
: base(parameter, Restrictions.Empty){ }
public override MetaObject Call(CallAction action, MetaObject[] args)
{
//You'll get MyMethod1 and MyMethod2 here (and what ever you call)
Console.WriteLine("Logic to invoke Method '{0}'", action.Name);
return this; //Return a meta object
}
}
You can have generic methods in a non-generic class.
Cool trick to emulate functional "wildcard" arguments (like '_' in Haskell) when using lambdas:
(_, b, __) => b.DoStuff(); // only interested in b here
Here's one I discovered recently which has been useful:
Microsoft.VisualBasic.Logging.FileLogTraceListener
MSDN Link [1]
This is a TraceListener implementation which has a lot of features, such as automatic log file roll over, which I previously would use a custom logging framework for. The nice thing is that it is a core part of .NET and is integrated with the Trace framework, so its easy to pick up and use immediately.
This is "hidden" because its in the Microsoft.VisualBasic assembly... but you can use it from C# as well.
[1] http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.logging.filelogtracelistener.aspxThe usage of the default keyword in generic code to return the default value for a type.
public class GenericList<T>
{
private class Node
{
//...
public Node Next;
public T Data;
}
private Node head;
//...
public T GetNext()
{
T temp = default(T);
Node current = head;
if (current != null)
{
temp = current.Data;
current = current.Next;
}
return temp;
}
}
[1] https://stackoverflow.com/questions/367378/returning-a-default-value-cThe built-in (2.0) MethodInvoker delegate is useful when you want to Invoke/BeginInvoke inline code. This avoids needing to create an actual delegate and separate method.
void FileMessageEvent(object sender, MessageEventArgs e)
{
if (this.InvokeRequired == true)
{
this.BeginInvoke((MethodInvoker)delegate {
lblMessage.Text=e.Message;
Application.DoEvents();
}
);
}
}
Resolves the error: "Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type".
Array initialization without specifying the array element type:
var pets = new[] { "Cat", "Dog", "Bird" };
string[] pets = {"Cat", "Dog", "Bird"};
- P Daddy
Properties to display when viewing components Properties in design view:
private double _Zoom = 1;
[Category("View")]
[Description("The Current Zoom Level")]
public double Zoom
{
get { return _Zoom;}
set { _Zoom = value;}
}
Makes things a lot easier for other users of your component libraries.
The already mentioned attributes DebuggerDisplay and DebuggerBrowsable control the visibility of elements and the textual value displayed. Simply overriding ToString() will cause the debugger to use the output of that method.
If you want more complex output you can use/create a Debugger Visualizer [1], several examples are available here [2].
Microsoft provide a debugger extension known as SOS [3]. This is an extremely powerful (though often confusing) extension which is an excellent way to diagnose 'leaks', more accurately unwanted references to objects no longer required.
Following these instructions [4] will allow you to step through the source of some parts of the framework.
Several enhancements and new features exist in Visual Studio 2010:
You can create delegates from extension methods as if they were regular methods, currying the this
parameter. For example,
static class FunnyExtension {
public static string Double(this string str) { return str + str; }
public static int Double(this int num) { return num + num; }
}
Func<string> aaMaker = "a".Double;
Func<string, string> doubler = FunnyExtension.Double;
Console.WriteLine(aaMaker()); //Prints "aa"
Console.WriteLine(doubler("b")); //Prints "bb"
Note that this won't work on extension methods that extend a value type; see this question [1].
[1] https://stackoverflow.com/questions/1016033/extension-methods-defined-on-value-types-cannot-be-used-to-create-delegates-whySomeEvent += OtherEvent.Raise
, where Raise
is a custom extension method. The difference between that and SomeEvent += OtherEvent
is left as an exercise to the reader (it's substantial). I may write a blog post about this at some point. - SLaks
HttpContext.Current.Server.Execute
is great for rendering HTML to strings for AJAX callbacks. You can use this with a component instead of piecing together HTML string snippets. I was able to cut page bloat down a couple of hundred KB with virtually no mess. I used it like this:
Page pageHolder = new Page();
UserControl viewControl = (UserControl)pageHolder.LoadControl(@"MyComponent.ascx");
pageHolder.Controls.Add(viewControl);
StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, false);
return output.ToString();
[field: NonSerialized]
public event EventHandler Event;
This way, the event listener is not serialized.
Just [NonSerialized] does not work, because NonSerializedAttribute can only be applied to fields.
I don't think someone has mentioned that appending ? after a value type name will make it nullable.
You can do:
DateTime? date = null;
DateTime is a structure.
Nullable<T>
is not a hidden feature... - Thomas Levesque
Four switch oddities [1] by Eric Lippert
[1] http://blogs.msdn.com/ericlippert/archive/2009/08/13/four-switch-oddities.aspxThe ability to use LINQ to do inline work on collections that used to take iteration and conditionals can be incredibly valuable. It's worth learning how all the LINQ extension methods can help make your code much more compact and maintainable.
I like
#if DEBUG
//Code run in debugging mode
#else
//Code run in release mode
#endif
Conditional
attribute is often a better solution than using #if
. msdn.microsoft.com/en-us/library/aa664622%28VS.71%29.aspx - Ergwun
I was reading thru the book "Pro ASP.NET MVC Framework" (APress) and observed something the author was doing with a Dictionary object that was foreign to me.
He added a new Key/Value Pair without using the Add() method. He then overwrote that same Key/Value pair without having to check if that key already existed. For example:
Dictionary<string, int> nameAgeDict = new Dictionary<string, int>();
nameAgeDict["Joe"] = 34; // no error. will just auto-add key/value
nameAgeDict["Joe"] = 41; // no error. key/value just get overwritten
nameAgeDict.Add("Joe", 30); // ERROR! key already exists
There are many cases where I don't need to check if my Dictionary already has a key or not and I just want to add the respective key/value pair (overwriting the existing key/value pair, if necessary.) Prior to this discovery, I would always have to check to see if the key already existed before adding it.
Not sure if this one has been mentioned or not (11 pages!!)
But the OptionalField
attribute for classes is amazing when you are versioning classes/objects that are going to be serialized.
http://msdn.microsoft.com/en-us/library/ms229752(VS.80).aspx
@Brad Barker
I think if you have to use nullable types, it's better to use Nullable<.T> rather than the question mark notation. It makes it eye-achingly obvious that magic is occurring. Not sure why anyone would ever want to use Nullable<.bool> though. :-)
Krzysztof Cwalina (one of the authors of Framwork Design Guidlines) has a good post here: http://blogs.msdn.com/kcwalina/archive/2008/07/16/Nullable.aspx
And Mike Hadlow has a nice post on Nullability Voodoo [1]
[1] http://mikehadlow.blogspot.com/2006/10/nullability-voodoo.htmlIn no particular order:
Lists<>
Mutex
The new property definitions shortcut in Framework 3.5.
In reading the book on development of the .NET framework. A good piece of advice is not to use bool to turn stuff on or off, but rather use ENums.
With ENums you give yourself some expandability without having to rewrite any code to add a new feature to a function.
Thought about @dp AnonCast and decided to try it out a bit. Here's what I come up with that might be useful to some:
// using the concepts of dp's AnonCast
static Func<T> TypeCurry<T>(Func<object> f, T type)
{
return () => (T)f();
}
And here's how it might be used:
static void Main(string[] args)
{
var getRandomObjectX = TypeCurry(GetRandomObject,
new { Name = default(string), Badges = default(int) });
do {
var obj = getRandomObjectX();
Console.WriteLine("Name : {0} Badges : {1}",
obj.Name,
obj.Badges);
} while (Console.ReadKey().Key != ConsoleKey.Escape);
}
static Random r = new Random();
static object GetRandomObject()
{
return new {
Name = Guid.NewGuid().ToString().Substring(0, 4),
Badges = r.Next(0, 100)
};
}
new modifier
Usage of the "new" modifier in C# is not exactly hidden but it's not often seen. The new modifier comes in handy when you need to "hide" base class members and not always override them. This means when you cast the derived class as the base class then the "hidden" method becomes visible and is called instead of the same method in the derived class.
It is easier to see in code:
public class BaseFoo
{
virtual public void DoSomething()
{
Console.WriteLine("Foo");
}
}
public class DerivedFoo : BaseFoo
{
public new void DoSomething()
{
Console.WriteLine("Bar");
}
}
public class DerivedBar : BaseFoo
{
public override void DoSomething()
{
Console.WriteLine("FooBar");
}
}
class Program
{
static void Main(string[] args)
{
BaseFoo derivedBarAsBaseFoo = new DerivedBar();
BaseFoo derivedFooAsBaseFoo = new DerivedFoo();
DerivedFoo derivedFoo = new DerivedFoo();
derivedFooAsBaseFoo.DoSomething(); //Prints "Foo" when you might expect "Bar"
derivedBarAsBaseFoo.DoSomething(); //Prints "FooBar"
derivedFoo.DoSomething(); //Prints "Bar"
}
}
[Ed: Do I get extra points for puns? Sorry, couldn't be helped.]
Literals can be used as variables of that type. eg.
Console.WriteLine(5.ToString());
Console.WriteLine(5M.GetType()); // Returns "System.Decimal"
Console.WriteLine("This is a string!!!".Replace("!!", "!"));
Just a bit of trivia...
There's quite a few things people haven't mentioned, but they have mostly to do with unsafe constructs. Here's one that can be used by "regular" code though:
The checked/unchecked keywords:
public static int UncheckedAddition(int a, int b)
{
unchecked { return a + b; }
}
public static int CheckedAddition(int a, int b)
{
checked { return a + b; } // or "return checked(a + b)";
}
public static void Main()
{
Console.WriteLine("Unchecked: " + UncheckedAddition(Int32.MaxValue, + 1)); // "Wraps around"
Console.WriteLine("Checked: " + CheckedAddition(Int32.MaxValue, + 1)); // Throws an Overflow exception
Console.ReadLine();
}
Instead of using int.TryParse() or Convert.ToInt32(), I like having a static integer parsing function that returns null when it can't parse. Then I can use ?? and the ternary operator together to more clearly ensure my declaration and initialization are all done on one line in a easy-to-understand way.
public static class Parser {
public static int? ParseInt(string s) {
int result;
bool parsed = int.TryParse(s, out result);
if (parsed) return result;
else return null;
}
// ...
}
This is also good to avoid duplicating the left side of an assignment, but even better to avoid duplicating long calls on the right side of an assignment, such as a database calls in the following example. Instead of ugly if-then trees (which I run into often):
int x = 0;
YourDatabaseResultSet data = new YourDatabaseResultSet();
if (cond1)
if (int.TryParse(x_input, x)){
data = YourDatabaseAccessMethod("my_proc_name", 2, x);
}
else{
x = -1;
// do something to report "Can't Parse"
}
}
else {
x = y;
data = YourDatabaseAccessMethod("my_proc_name",
new SqlParameter("@param1", 2),
new SqlParameter("@param2", x));
}
You can do:
int x = cond1 ? (Parser.ParseInt(x_input) ?? -1) : y;
if (x >= 0) data = YourDatabaseAccessMethod("my_proc_name",
new SqlParameter("@param1", 2),
new SqlParameter("@param2", x));
Much cleaner and easier to understand
ParseIntOrDefault(string input, int default)
? - MattDavey
Math.Max and Min to check boundaries: I 've seen this in a lot of code:
if (x < lowerBoundary)
{
x = lowerBoundary;
}
I find this smaller, cleaner and more readable:
x = Math.Max(x, lowerBoundary);
Or you can also use a ternary operator:
x = ( x < lowerBoundary) ? lowerBoundary : x;
i = MinMax(i,a,b)
; - sehe
i = MinMax(i,minval,maxval)
. I try not to interpret Min or Max differently, but I guess what sometimes happens is that I misread Min(a,100) to mean something like 'a, but at a minimum of 100'. The catch is in that when you want to impose a maximum you need to use the Min() function, and viceversa. It catches me out all the time. Even when I'm on my guard :) - sehe
MinMax(i,i,maxval) === Min(i, maxval)
and MinMax(i,minval,i) === Max(i, minval)
. I find that this confuses the heck out me when seeing them next to eachother, but never confuses me when using MinMax in isolation. Min and Max in isolation do confuse me regularly. - sehe
Mixins are a nice feature. Basically, mixins let you have concrete code for an interface instead of a class. Then, just implement the interface in a bunch of classes, and you automatically get mixin functionality. For example, to mix in deep copying into several classes, define an interface
internal interface IPrototype<T> { }
Add functionality for this interface
internal static class Prototype
{
public static T DeepCopy<T>(this IPrototype<T> target)
{
T copy;
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, (T)target);
stream.Seek(0, SeekOrigin.Begin);
copy = (T) formatter.Deserialize(stream);
stream.Close();
}
return copy;
}
}
Then implement interface in any type to get a mixin.
Regarding foreach
: It does not use 'duck typing', as duck typing IMO refers to a runtime check. It uses structural type checking (as opposed to nominal) at compile time to check for the required method in the type.
(I just used this one) Set a field null and return it without an intermediate variable:
try
{
return _field;
}
finally
{
_field = null;
}
This isn't a C# specific feature but it is an addon that I find very useful. It is called the Resource Refactoring Tool. It allows you to right click on a literal string and extract it into a resource file. It will search the code and find any other literal strings that match and replace it with the same resource from the Resx file.
http://www.codeplex.com/ResourceRefactoring
I call this AutoDebug because you can drop right into debug where and when you need based on a bool value which could also be stored as a project user setting as well.
Example:
//Place at top of your code
public UseAutoDebug = true;
//Place anywhere in your code including catch areas in try/catch blocks
Debug.Assert(!this.UseAutoDebug);
Simply place the above in try/catch blocks or other areas of your code and set UseAutoDebug to true or false and drop into debug anytime you wish for testing.
You can leave this code in place and toggle this feature on and off when testing, You can also save it as a Project Setting, and manually change it after deployment to get additional bug information from users when/if needed as well.
You can see a functional and working example of using this technique in this Visual Studio C# Project Template here, where it is used heavily:
http://code.msdn.microsoft.com/SEHE
Method groups aren't well known.
Given:
Func<Func<int,int>,int,int> myFunc1 = (i, j) => i(j);
Func<int, int> myFunc2 = i => i + 2;
You can do this:
var x = myFunc1(myFunc2, 1);
instead of this:
var x = myFunc1(z => myFunc2(z), 1);
List<int> items = { 1, 3, 5, 7, 11} ;
, that you can do var total = items.Sum(myFunc2);
instead of var total = items.Sum(i => myFunc2(i));
. - ANeves
I am so so late to this question, but I wanted to add a few that I don't think have been covered. These aren't C#-specific, but I think they're worthy of mention for any C# developer.
AmbientValueAttribute
[1]
This is similar to DefaultValueAttribute
, but instead of providing the value that a property defaults to, it provides the value that a property uses to decide whether to request its value from somewhere else. For example, for many controls in WinForms, their ForeColor
and BackColor
properties have an AmbientValue
of Color.Empty
so that they know to get their colors from their parent control.
IsolatedStorageSettings
[2]
This is a Silverlight one. The framework handily includes this sealed class for providing settings persistence at both the per-application and per-site level.
Using extension methods, flag enumeration use can be a lot more readable.
public static bool Contains(
this MyEnumType enumValue,
MyEnumType flagValue)
{
return ((enumValue & flagValue) == flagValue);
}
public static bool ContainsAny(
this MyEnumType enumValue,
MyEnumType flagValue)
{
return ((enumValue & flagValue) > 0);
}
This makes checks for flag values nice and easy to read and write. Of course, it would be nicer if we could use generics and enforce T to be an enum, but that isn't allowed. Perhaps dynamic
will make this easier.
I find it incredible what type of trouble the compiler goes through to sugar code the use of Outer Variables:
string output = "helo world!";
Action action = () => Console.WriteLine(output);
output = "hello!";
action();
This actually prints hello!
. Why? Because the compiler creates a nested class for the delegate, with public fields for all outer variables and inserts setting-code before every single call to the delegate :) Here is above code 'reflectored':
Action action;
<>c__DisplayClass1 CS$<>8__locals2;
CS$<>8__locals2 = new <>c__DisplayClass1();
CS$<>8__locals2.output = "helo world!";
action = new Action(CS$<>8__locals2.<Main>b__0);
CS$<>8__locals2.output = "hello!";
action();
Pretty cool I think.
I couldn't figure out what use some of the functions in the Convert
class had (such as Convert.ToDouble(int), Convert.ToInt(double)) until I combined them with Array.ConvertAll
:
int[] someArrayYouHaveAsInt;
double[] copyOfArrayAsDouble = Array.ConvertAll<int, double>(
someArrayYouHaveAsInt,
new Converter<int,double>(Convert.ToDouble));
Which avoids the resource allocation issues that arise from defining an inline delegate/closure (and slightly more readable):
int[] someArrayYouHaveAsInt;
double[] copyOfArrayAsDouble = Array.ConvertAll<int, double>(
someArrayYouHaveAsInt,
new Converter<int,double>(
delegate(int i) { return (double)i; }
));
Having just learned the meaning of invariance, covariance and contravariance, I discovered the in [1] and out [2] generic modifiers that will be included in .NET 4.0. They seem obscure enough that most programmers would not know about them.
There's an article [3] at Visual Studio Magazine which discusses these keywords and how they will be used.
[1] http://msdn.microsoft.com/en-us/library/dd469484(VS.100).aspxThe data type can be defined for an enumeration:
enum EnumName : [byte, char, int16, int32, int64, uint16, uint32, uint64]
{
A = 1,
B = 2
}
The Yield keyword is often overlooked when it has a lot of power. I blogged about it awhile ago and discussed benefits (differed processing) and happens under the hood of yield to help give a stronger understanding.
[1] http://jxs.me/2010/05/14/using-yield-in-c/Pointers in C#.
They can be used to do in-place string manipulation. This is an unsafe feature so the unsafe keyword is used to mark the region of unsafe code. Also note how the fixed keyword is used to indicate that the memory pointed to is pinned and cannot be moved by the GC. This is essential a pointers point to memory addresses and the GC can move the memory to different address otherwise resulting in an invalid pointer.
string str = "some string";
Console.WriteLine(str);
unsafe
{
fixed(char *s = str)
{
char *c = s;
while(*c != '\0')
{
*c = Char.ToUpper(*c++);
}
}
}
Console.WriteLine(str);
I wouldn't ever do it but just for the sake of this question to demonstrate this feature.
I especially like the nullable DateTime. So if you have some cases where a Date is given and other cases where no Date is given I think this is best to use and IMHO easier to understand as using DateTime.MinValue
or anything else...
DateTime? myDate = null;
if (myDate.HasValue)
{
//doSomething
}
else
{
//soSomethingElse
}
Open generics are another handy feature especially when using Inversion of Control [1]:
container.RegisterType(typeof(IRepository<>), typeof(NHibernateRepository<>));
[1] http://en.wikipedia.org/wiki/Inversion_of_controlHaving read through all 9 pages of this I felt I had to point out a little unknown feature...
This was held true for .NET 1.1, using compression/decompression on gzipped files, one had to either:
It is underused, that I did not know about, (still use ICSharpCode.ZipLib still, even with .NET 2/3.5) was that it was incorporated into the standard BCL version 2 upwards, in the System.IO.Compression namespace... see the MSDN page " GZipStream Class [2]".
[1] http://www.icsharpcode.net/OpenSource/SharpZipLib/I find the use of the conditional break function in Visual Studio very useful. I like the way it allows me to set the value to something that, for example can only be met in rare occasions and from there I can examine the code further.
This means T must have a public parameterless constructor :
class MyClass<T> where T : new()
{
}
Accessing local variables from anonymous methods allows you to wrap just about any code with new control flow logic, without having to factor out that code into another method. Local variables declared outside the method are available inside the method such as the endOfLineChar
local variable in the example here:
http://aaronls.wordpress.com/2010/02/02/retrying-on-exception-conditionally/
@lainMH,
Nullable booleans are useful when retrieving values from a database that are nullable and when putting values back in. Sometimes you want to know the field has not been set.
Reflection Emit and Expression trees come to mind...
Don't miss Jeffrey Richter's CLR via C# and Jon Skeet's
See here for some resources:
http://www.codeproject.com/KB/trace/releasemodebreakpoint.aspx
http://www.codeproject.com/KB/dotnet/Creating_Dynamic_Types.aspx
http://www.codeproject.com/KB/cs/lambdaexpressions.aspx
System.Runtime.Remoting.Proxies.RealProxy [1]
It enables Aspect Oriented Programming in C#, and you can also do a lot of other fancy stuff with it.
[1] http://msdn.microsoft.com/en-us/library/system.runtime.remoting.proxies.realproxy.aspxI find this technique interesting while working with linqxml:
public bool GetFooSetting(XElement ndef){
return (bool?)ndef.Element("MyBoolSettingValue") ?? true;
}
as opposed to:
public bool GetFooSetting(XElement ndef){
return ndef.Element("MyBoolSettingValue") != null ? bool.Parse(ndef.Element("MyBoolSettingValue") ) : true;
}
The generic event handler:
public event EventHandler<MyEventArgs> MyEvent;
This way you don't have to declare your own delegates all the time,
I didn't discover - for almost a year - that Strongly Typed DataRows contain an Is[ColumnName]Null() method.
For example:
Units.UnitsDataTable dataTable = new Units.UnitsDataTable();
foreach (Units.UnitsRow row in dataTable.Rows)
{
if (row.IsPrimaryKeyNull())
//....
if (row.IsForeignKeyNull())
//....
}
Is constructor chain already cited?
namespace constructorChain {
using System;
public class Class1 {
public string x;
public string y;
public Class1() {
x = "class1";
y = "";
}
public Class1(string y)
: this() {
this.y = y;
}
}
public class Class2 : Class1 {
public Class2(int y)
: base(y.ToString()) {
}
}
}
...
constructorChain.Class1 c1 = new constructorChain.Class1();
constructorChain.Class1 c12 = new constructorChain.Class1("Hello, Constructor!");
constructorChain.Class2 c2 = new constructorChain.Class2(10);
Console.WriteLine("{0}:{1}", c1.x, c1.y);
Console.WriteLine("{0}:{1}", c12.x, c12.y);
Console.WriteLine("{0}:{1}", c2.x, c2.y);
Console.ReadLine();
FIXED / Power of Pointers in C# - This topic is too big, but I will just outline simple things.
In C we had facility of loading structure like...
struct cType{
char type[4];
int size;
char name[50];
char email[100];
}
cType myType;
fread(file, &mType, sizeof(mType));
We can use fixed keyword in "unsafe" method to read byte array aligned structure.
[Layout(LayoutKind.Sequential, Pack=1)]
public unsafe class CType{
public fixed byte type[4];
public int size;
public fixed byte name[50];
public fixed byte email[100];
}
Method 1 (Reading from regular stream in to byte buffer and mapping byte array to individual bytes of struct)
CType mType = new CType();
byte[] buffer = new byte[Marshal.SizeOf(CType)];
stream.Read(buffer,0,buffer.Length);
// you can map your buffer back to your struct...
fixed(CType* sp = &mType)
{
byte* bsp = (byte*) sp;
fixed(byte* bp = &buffer)
{
for(int i=0;i<buffer.Length;i++)
{
(*bsp) = (*bp);
bsp++;bp++;
}
}
}
Method 2, you can map Win32 User32.dll's ReadFile to directly read bytes...
CType mType = new CType();
fixed(CType* p = &mType)
{
User32.ReadFile(fileHandle, (byte*) p, Marshal.SizeOf(mType),0);
}
I like to use the using directive to rename some classes for easy reading like this:
// defines a descriptive name for a complexed data type
using MyDomainClassList = System.Collections.Generic.List<
MyProjectNameSpace.MyDomainClass>;
....
MyDomainClassList myList = new MyDomainClassList();
/* instead of
List<MyDomainClass> myList = new List<MyDomainClass>();
*/
This is also very handy for code maintenance. If you need to change the class name, there is only one place you need to change. Another example:
using FloatValue = float; // you only need to change it once to decimal, double...
....
FloatValue val1;
...
Zero parameter Lambdas
()=>Console.ReadLine()
I didn't see this:
for (;;);
The same as
while (true) ;
One that I just learned recently is that you can still call methods on a nullable value [1]....
It turns out what when you have a nullable value:
decimal? MyValue = null;
where you might think you would have to write:
MyValue == null ? null : MyValue .ToString()
you can instead write:
MyValue.ToString()
I've been aware that I could call MyValue.HasValue and MyValue.Value...but it didn't fully click that I could call ToString().
[1] https://stackoverflow.com/questions/1242883/is-there-a-better-way-to-write-this-line-of-c-code-in-c3-0This will not compile:
namespace ns
{
class Class1
{
Nullable<int> a;
}
}
The type or namespace name 'Nullable' could not be found (are you missing a using directive or an assembly reference?) <-- missing 'using System;
'
But
namespace ns
{
class Class1
{
int? a;
}
}
will compile! (.NET 2.0).
int
vs Int32
. - MattDavey
I apologize if this one has been mentioned, but I use this a lot.
An add-in for Visual Studio was developed by Alex Papadimoulis. It's used for pasting regular text as string, string builder, comment or region.
In this plugin (I also don't know if this has been mentioned) I noticed that strings are pasted with the string literal prefix:
@
I knew about these, but I didn't know about using a double quote within a literal to escape the quote.
For example
string s = "A line of text" + Environment.NewLine + "Another with a \"quote\"!!";
can be expressed as
string s = @"A line of text
Another with a ""quote""!!";
I like the EditorBrowsableAttribute [1]. It lets you control whether a method/property is displayed or not in Intellisense. You can set the values to Always, Advanced, or Never.
From MSDN [2]...
Remarks
EditorBrowsableAttribute is a hint to a designer indicating whether a property or method is to be displayed. You can use this type in a visual designer or text editor to determine what is visible to the user. For example, the IntelliSense engine in Visual Studio uses this attribute to determine whether to show a property or method.
In Visual C#, you can control when advanced properties appear in IntelliSense and the Properties Window with the Hide Advanced Members setting under Tools | Options | Text Editor | C#. The corresponding EditorBrowsableState is Advanced.
[1] http://msdn.microsoft.com/en-us/library/system.componentmodel.editorbrowsableattribute.aspx__arglist as well
[DllImport("msvcrt40.dll")]
public static extern int printf(string format, __arglist);
static void Main(string[] args)
{
printf("Hello %s!\n", __arglist("Bart"));
}
The Action and Func delegate helpers in conjunction with lambda methods. I use these for simple patterns that need a delegate to improve readability. For example, a simple caching pattern would be to check if the requested object exists in the cache. If it does exist: return the cached object. If it doesn't exist, generate a new instance, cache the new instance and return the new instance. Rather that write this code 1000 times for each object I may store/retrieve from the cache I can write a simple pattern method like so...
private static T CachePattern<T>(string key, Func<T> create) where T : class
{
if (cache[key] == null)
{
cache.Add(key, create());
}
return cache[key] as T;
}
... then I can greatly simplify my cache get/set code by using the following in my custom cache manager
public static IUser CurrentUser
{
get
{
return CachePattern<IUser>("CurrentUserKey", () => repository.NewUpUser());
}
}
Now simple "everyday" code patterns can be written once and reused much more easily IMHO. I don't have to go write a delegate type and figure out how I want to implement a callback, etc. If I can write it in 10 seconds I'm much less apt. to resort to cutting/pasting simple code patterns whether they be lazy initialization and some other examples shown above...
Empty blocks with braces are allowed.
You can write code like this
{
service.DoTonsOfWork(args);
}
It's helpful when you want to try something without a using
or try... finally
that you've already written.
//using(var scope = new TransactionScope)
{
service.DoTonsOfWork(args);
}
Debug.Indent()
and a Debug.Unindent
. - Ryan Lundy
Nullable.GetValueOrDefault ?
??
operator for nullable types. - John Alexiou
One interesting thing I've learned is that different parts of the framework and C# language were written at different times, hence inconsistencies. For example, the framework itself violates many FxCop rules because the rules weren't all in place when the framework was written.
Also, the using statement was intended for delinieating "scopes" and not specifically for disposing resources. It was written after the lock statement. Eric Gunnerson once mentioned [1] something along the lines of that if the using statement came first, they might have not needed to write the lock statement (though who knows, maybe they would have anyways), because the using statement might have been sufficient.
[1] http://haacked.com/archive/2004/05/27/DifficultiesOfLanguageDesign.aspxTryParse method for each primitive type is great when validating user input.
double doubleValue
if (!Double.TryParse(myDataRow("myColumn"), out doubleValue))
{
// set validation error
}
The #region {string} and #endregion pair is very neat for grouping code (outlining).
#region Using statements
using System;
using System.IO;
using ....;
using ....;
#endregion
The code block can be compressed to a single describing line of text. Works inside functions aswell.
I think a lot of people know about pointers in C but are not sure if it works in C#. You can use pointers in C# in an unsafe context:
static void Main()
{
int i;
unsafe
{
// pointer pi has the address of variable i
int* pi = &i;
// pointer ppi has the address of variable pi
int** ppi = π
// ppi(addess of pi) -> pi(addess of i) -> i(0)
i = 0;
// dereference the pi, i.e. *pi is i
Console.WriteLine("i = {0}", *pi); // output: i = 0
// since *pi is i, equivalent to i++
(*pi)++;
Console.WriteLine("i = {0}", *pi); // output: i = 1
// since *ppi is pi, one more dereference *pi is i
// equivalent to i += 2
**ppi += 2;
Console.WriteLine("i = {0}", *pi);// output: i = 3
}
Console.ReadLine();
}
This may be pretty basic to database application developers, but it took me a while to realize that null is not the same as DBNull.value.
You have to use DBNull.value when you want to see if a value from a database record is null.
Just learned the joys of [UnmanagedFunctionPointerAttribute(CallingConvention.CDecl)]
from trying to interface with an unmanaged C++ function library that defined callbacks without __stdcall.
Framework Feature
I don't know but I was quite suprised about VisualStyleRenderer [1] and the whole System.Windows.Forms.VisualStyles-Namespace [2]. Pretty cool!
[1] http://msdn.microsoft.com/de-de/library/system.windows.forms.visualstyles.visualstylerenderer(VS.85).aspxThe InternalsVisibleToAttribute specifies that types that are ordinarily visible only within the current assembly are visible to another assembly. Article on msdn [1]
[1] http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspxIf you have the search textbox in your Visual Studio toolbar, you can type ">of Program.cs" to open the file Program.cs
A few from me - make of them what you will.
The attribute:
[assembly::InternalsVisibleTo("SomeAssembly")]
Allows you to expose out the internal methods/properties or data from your assembly to another assembly called 'SomeAssembly'. All protected/private stuff remains hidden.
Static constructors ( otherwise called 'Type Constructor' )
public MyClass
{
public static MyClass()
{
// type init goes here
}
......
}
The keyword internal
. So useful in so many ways.
Ability to create instance of the type based on the generic parameter like this
new T();
Marketing events as non-serializable:
[field:NonSerializable]
public event SomeDelegate SomeEvent;
Generic constraints:
//Constructor constraint, T has a default empty constructor
class Node<K,T> where T : new()
{
}
//Reference\Value Type constraints
//T is a struct
public class MyClass<T> where T : struct
{...}
//T is a reference type
public class MyClass<T> where T : class
{...}
public class MyClass<T> where T : SomeBaseClass, ISomeInterface
{...}
How about Expression Trees [1]? They are the heart of LINQ and allow for defered execution:
Taken from David Hayden's blog [2]:
In C# 3.0, you can define a delegate as follows using a lambda expression:
Func<int,int> f = x => x + 1;
This delegate is compiled into executable code in your application and can be called as such:
var three = f(2); // 2 + 1
The code works as you would expect. Nothing fancy here.
Expression Trees
When you define the delegate as an Expression Tree by using System.Query.Expression:
Expression<Func<int,int>> expression = x => x + 1;
The delegate is no longer compiled into executable code, but compiled as data that can be converted and compiled into the original delegate.
To actually use the delegate represented as an Expression Tree in your application, you would have to compile and invoke it in your application:
var originalDelegate = expression.Compile();
var three = originalDelegate.Invoke(2);
[1] http://msdn.microsoft.com/en-us/library/bb397951.aspxA lot of this is explained already, in the standard [1]. It's a good read for any beginner as well as expert, it's a lot to read, but it's the official standard, and it's filled with juicy details.
Once you fully understand C#, it's time to take this further to understand the fundamentals of the Common Language Infrastructure [2]. The architecture and underpinnings of C#.
I've met a variety of programmers that don't know the difference between an object and a ValueType except the adherent limitations thereof.
Familiarize yourself with these two documents and you'll never become that person.
[1] http://www.ecma-international.org/publications/standards/Ecma-334.htmGenerics and the Curiously-Recurring Template Pattern [1] really help with some static method/property declarations.
Suppose you are building a class hierarchy:
class Base
{
}
class Foo: Base
{
}
class Bar: Base
{
}
Now, you want to declare static methods on your types that should take parameters (or return values) of the same type or static properties of the same type. For example, you want:
class Base
{
public static Base Get()
{
// Return a suitable Base.
}
}
class Foo: Base
{
public static Foo Get()
{
// Return a suitable Foo.
}
}
class Bar: Base
{
public static Bar Get()
{
// Return a suitable Bar.
}
}
If these static methods basically all do the same thing, then you have lots of duplicated code on your hands. One solution would be to drop type safety on the return values and to always return type Base
. However, if you want type safety, then the solution is to declare the Base
as:
class Base<T> where T: Base<T>
{
public static T Get<T>()
{
// Return a suitable T.
}
}
and you Foo
and Bar
as:
class Foo: Base<Foo>
{
}
class Bar: Base<Bar>
{
}
This way, they will automatically get their copies of the static methods.
This also works wonders to encapsulate the Singleton pattern in a base class (I know the code below is not thread-safe, it just to demonstrate a point):
public class Singleton<T> where T: Singleton<T>, new()
{
public static T Instance { get; private set; }
static Singleton<T>()
{
Instance = new T();
}
}
I realize that this forces you to have a public parameterless constructor on your singleton subclass but there is no way to avoid that at compile time without a where T: protected new()
construct; however one can use
reflection
[2] to invoke the protected/private parameterless constructor of the sub-class at runtime to achieve that.
protected abstract T CreateInstance()
forcing the child class to override that and then in Instance
property you'd call the method if there's Instance == null ? - chakrit
I love abusing the fact that static templated classes don't share their static members.
Here's a threadsafe (at creation time) and cheap substitute to any Dictionary<Type,...>
when the Type
instance is known at compile-time.
public static class MyCachedData<T>{
static readonly CachedData Value;
static MyCachedData(){
Value=// Heavy computation, such as baking IL code or doing lots of reflection on a type
}
}
Cheers, Florian
Convert enum values to a string value
Given the enum
enum Country
{
UnitedKingdom,
UnitedStates,
UnitedArabEmirates,
}
using it:
public static void PrintEnumAsString( Country country )
{
Console.Writeline( country.ToString() );
}
will print the name of the enum value as a string, e.g. "UnitedKingdom"
I just want to mention (because of the OP metioning where T : struct) that one of the C# compiler gotchas is that
where T : Enum
will NOT compile. It throws the error "Constraint cannot be special class 'System.Enum'".
where T : System.Enum
, with a captial E will. - John Leidegren
Collection Initializer inside Object Initializer:
MailMessage mail = new MailMessage {
To = { new MailAddress("a@example.com"), new MailAddress("b@example.com") },
Subject = "Password Recovery"
};
You can initialize a whole tree in a single expression.
I am bit late in this conversation and I would like to contribute the following. It may be a new thing for some developers.
public class User
{
public long UserId { get; set; }
public String Name { get; set; }
public String Password { get; set; }
public String Email { get; set; }
}
The usual way to declare and initialize it is with a constructor or like following.
User user = new User();
user.UserId = 1;
user.Name = "myname";
etc
But I learned following way to initialize it. I know Visual Basic developers will love it because it's like with operator available only in VB.NET and not in C# that is as follows.
User user = new User()
{
UserId = 1,
Name = "myname",
Email = "myemail@domain.com",
Password = "mypassword"
};
With
are wayyy more awesome :) - chakrit
One of the most useful features Visual Studio has is "Make object id". It generates an id and "attaches" to the object so wherever you look at the object you will also see the id (regardless of the thread).
While debugging right click on the variable tooltip and there you have it. It also works on watched/autos/locals variables.
This relates to static constructors. This is a method for performing static destruction (i.e. cleaning up resources when the program quits).
First off the class:
class StaticDestructor
{
/// <summary>
/// The delegate that is invoked when the destructor is called.
/// </summary>
public delegate void Handler();
private Handler doDestroy;
/// <summary>
/// Creates a new static destructor with the specified delegate to handle the destruction.
/// </summary>
/// <param name="method">The delegate that will handle destruction.</param>
public StaticDestructor(Handler method)
{
doDestroy = method;
}
~StaticDestructor()
{
doDestroy();
}
}
Then as a member of the class you wish to have a "static destructor" do:
private static readonly StaticDestructor destructor = new StaticDestructor
(
delegate()
{
//Cleanup here
}
);
This will now be called when final garbage collection occurs. This is useful if you absolutely need to free up certain resources.
A quick and dirty program exhibiting this behavior:
using System;
namespace TestStaticDestructor
{
class StaticDestructor
{
public delegate void Handler();
private Handler doDestroy;
public StaticDestructor(Handler method)
{
doDestroy = method;
}
~StaticDestructor()
{
doDestroy();
}
}
class SomeClass
{
static SomeClass()
{
Console.WriteLine("Statically constructed!");
}
static readonly StaticDestructor destructor = new StaticDestructor(
delegate()
{
Console.WriteLine("Statically destructed!");
}
);
}
class Program
{
static void Main(string[] args)
{
SomeClass someClass = new SomeClass();
someClass = null;
System.Threading.Thread.Sleep(1000);
}
}
}
When the program exits, the "static destructor" is called.
I don't condone it, but I was surprised that goto [1] is still around ducks incoming projectiles
[1] http://msdn.microsoft.com/en-us/library/13940fs2(VS.100).aspxgoto
on occasion. There is nothing wrong with it. - ChaosPandion
goto
to is knock down C# developers down a notch when they get elitist against VB.NET--I code both, so I have to have ammo that goes both ways :D - STW
goto
is for those rare circumstances where you can't jump out of a control structure cleanly any other way. - David R Tribble
goto
in those cases is the best thing to do. - Arseni Mourzenko
You can combine the protected
and internal
accessor to make it public within the same assembly, but protected in a diffrent assembly. This can be used on fields, properties, method and even constants.
Returning IQueryable projections
protected void LdsPostings_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
var dc = new MyDataContext();
var query = dc.Posting.AsQueryable();
if (isCondition1)
{
query = query.Where(q => q.PostedBy == Username);
e.Result = QueryProjection(query);
return;
}
...
if (isConditionN)
{
query = query.Where(q => q.Status.StatusName == "submitted");
query = query.Where(q => q.ReviewedBy == Username);
e.Result = QueryProjection(query);
return;
}
}
and rather than coding the projection multiple times, create a single method:
private IQueryable QueryProjection(IQueryable<Posting> query)
{
return query.Select(p => new
{
p.PostingID,
p.Category.CategoryName,
p.Type.TypeName,
p.Status.StatusName,
p.Description,
p.Updated,
p.PostedBy,
p.ReviewedBy,
});
}
ContextBoundObject
Not so much a C# thing as a .NET thing. It's another way of achieving DI although it can be hardwork. And you have to inherit from it which can be off putting.
http://msdn.microsoft.com/en-us/library/system.contextboundobject.aspx
I've used it to add logging when I decorate a class/method with a custom logging attribute.
double dSqrd = Math.Pow(d,2.0);
is more accurate than
double dSqrd = d * d; // Here we can lose precision
ThreadStaticAttribute is a favorite of mine. Also, NonSerializableAttribute is useful. (Can you tell I do a lot of server stuff using remoting?)
ViewState getters can be one-liners.
Using a default value:
public string Caption
{
get { return (string) (ViewState["Caption"] ?? "Foo"); }
set { ViewState["Caption"] = value; }
}
public int Index
{
get { return (int) (ViewState["Index"] ?? 0); }
set { ViewState["Index"] = value; }
}
Using null as the default:
public string Caption
{
get { return (string) ViewState["Caption"]; }
set { ViewState["Caption"] = value; }
}
public int? Index
{
get { return (int?) ViewState["Index"]; }
set { ViewState["Index"] = value; }
}
This works for anything backed by a dictionary.
Only for reference - enum binary operations using the extension method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
namespace BinaryOpGenericTest
{
[Flags]
enum MyFlags
{
A = 1,
B = 2,
C = 4
}
static class EnumExtensions
{
private static Dictionary<Type, Delegate> m_operations = new Dictionary<Type, Delegate>();
public static bool IsFlagSet<T>(this T firstOperand, T secondOperand)
where T : struct
{
Type enumType = typeof(T);
if (!enumType.IsEnum)
{
throw new InvalidOperationException("Enum type parameter required");
}
Delegate funcImplementorBase = null;
m_operations.TryGetValue(enumType, out funcImplementorBase);
Func<T, T, bool> funcImplementor = funcImplementorBase as Func<T, T, bool>;
if (funcImplementor == null)
{
funcImplementor = buildFuncImplementor(secondOperand);
}
return funcImplementor(firstOperand, secondOperand);
}
private static Func<T, T, bool> buildFuncImplementor<T>(T val)
where T : struct
{
var first = Expression.Parameter(val.GetType(), "first");
var second = Expression.Parameter(val.GetType(), "second");
Expression convertSecondExpresion = Expression.Convert(second, typeof(int));
var andOperator = Expression.Lambda<Func<T, T, bool>>(Expression.Equal(
Expression.And(
Expression.Convert(first, typeof(int)),
convertSecondExpresion),
convertSecondExpresion),
new[] { first, second });
Func<T, T, bool> andOperatorFunc = andOperator.Compile();
m_operations[typeof(T)] = andOperatorFunc;
return andOperatorFunc;
}
}
class Program
{
static void Main(string[] args)
{
MyFlags flag = MyFlags.A | MyFlags.B;
Console.WriteLine(flag.IsFlagSet(MyFlags.A));
Console.WriteLine(EnumExtensions.IsFlagSet(flag, MyFlags.C));
Console.ReadLine();
}
}
}
Well... Don't use it, but a lot of people don't know C# supports the evil goto:)
static void Example()
{
int i = 0;
top:
Console.WriteLine(i.ToString());
if (i == 0)
{
i++;
goto top;
}
}
goto case...
variety within a switch statement, but it's good to have it when it's what you need. Goto's inclusion in the language is for those occasional times when it really is the clearest construct, not to be avoided at all costs. - P Daddy
Definitely the Func<> types when used with statement lambdas in .NET 3.5. These allow customizable functions, and can be a great aid in offering user customizable objects without subclassing them or resorting to some limited system like keeping track of a variable that lists what button or key the user wants to monitor. Also, they can be called just like regular methods and can be assigned like variables. The only downside that I can think of is that you're limited to 5 arguments! Although by that point you might want to consider a different solution... Edit: Providing some examples.
...
public Func<InputHelper, float> _horizontalCameraMovement = (InputHelper input) =>
{
return (input.LeftStickPosition.X * _moveRate) * _zoom;
}
public Func<InputHelper, float> _verticalCameraMovement = (InputHelper input) =>
{
return (-input.LeftStickPosition.Y * _moveRate) * _zoom;
}
...
public void Update(InputHelper input)
{
...
position += new Vector2(_horizontalCameraMovement(input), _verticalCameraMovement(input));
...
}
In this example, you can write a function that does arbitrary calculation and returns a float that will determine the amount that the camera moves by. Not the best code but it gets the point across.
private int foo;
public int FooProperty {
get
{
if (_onFooGotten() == true)
return _foo;
}
set
{
if (onFooSet() == true)
_foo = value;
}
}
...
public Func<bool> _onFooGotten = () =>
{
//do whatever...
return true;
}
public Func<bool> _onFooSet = () =>
{
//do whatever...
return true;
}
This isn't the best example (as I haven't really explored this use yet) but it shows an example of using a lambda function for a quick event raiser without the hassle of delegates. Edit: thought of another one. Nullables! The closest thing C# has to optional parameters.
If you are trying to create a comma delimited string from a list of items:
string[] itemList = { "Example 1", "Example 2", "Example 3" };
CommaDelimitedStringCollection commaStr = new CommaDelimitedStringCollection();
commaStr.AddRange(itemList);
//outputs Example 1,Example 2,Example 3
Look here [1] for another example.
[1] http://blog.crowe.co.nz/archive/2007/08/25/c---How-to-create-a-comma-seperated-string-from.aspxvar cdsc = new CommaDelimitedStringCollection { "Example 1", "Example 2", "Example 3" };
(also, string.Join takes the cake) - sehe
Keeps DataGridView from showing the property:
[System.ComponentModel.Browsable(false)]
public String LastActionID{get; private set;}
Lets you set a friendly display for components (like a DataGrid or DataGridView):
[System.ComponentModel.DisplayName("Last Action")]
public String LastAction{get; private set;}
For your backing variables, if you don't want anything accessing them directly this makes it tougher:
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
private DataController p_dataSources;
At first - DebuggerTypeProxy [1].
[DebuggerTypeProxy(typeof(HashtableDebugView))]
class MyHashtable : Hashtable
{
private const string TestString =
"This should not appear in the debug window.";
internal class HashtableDebugView
{
private Hashtable hashtable;
public const string TestStringProxy =
"This should appear in the debug window.";
// The constructor for the type proxy class must have a
// constructor that takes the target type as a parameter.
public HashtableDebugView(Hashtable hashtable)
{
this.hashtable = hashtable;
}
}
}
At second:
[1] http://msdn.microsoft.com/en-us/library/d8eyd8zc.aspxThe following one is not hidden, but it's quite implicit. I don't know whether samples like the following one have been published here, and I can't see are there any benefits (probably there are none), but I'll try to show a "weird" code. The following sample simulates for
statement via functors in C# (delegates / anonymous delegates [lambdas]) and closures. Other flow statements like if
, if/else
, while
and do/whle
are simulated as well, but I'm not sure for switch
(perhaps, I'm too lazy :)). I've compacted the sample source code a little to make it more clear.
private static readonly Action EmptyAction = () => { };
private static readonly Func<bool> EmptyCondition = () => { return true; };
private sealed class BreakStatementException : Exception { }
private sealed class ContinueStatementException : Exception { }
private static void Break() { throw new BreakStatementException(); }
private static void Continue() { throw new ContinueStatementException(); }
private static void For(Action init, Func<bool> condition, Action postBlock, Action statement) {
init = init ?? EmptyAction;
condition = condition ?? EmptyCondition;
postBlock = postBlock ?? EmptyAction;
statement = statement ?? EmptyAction;
for ( init(); condition(); postBlock() ) {
try {
statement();
} catch ( BreakStatementException ) {
break;
} catch ( ContinueStatementException ) {
continue;
}
}
}
private static void Main() {
int i = 0; // avoiding error "Use of unassigned local variable 'i'" if not using `for` init block
For(() => i = 0, () => i < 10, () => i++,
() => {
if ( i == 5 )
Continue();
Console.WriteLine(i);
}
);
}
If I'm not wrong, this approach is pretty relative to the functional programming practice. Am I right?
The "TODO" property and the tasks list
//TODO: [something]
Adding that to your code (the spacing is important) throws an item in your task list, and double clicking the item will jump you to the appropriate location in your code.
I didn't knew about Generic methods which could help avoid using Method Overloadding. Below are overloaded methods to print int and double numbers.
private static void printNumbers(int [] intNumbers)
{
foreach(int element in intNumbers)
{
Console.WriteLine(element);
}
}
private static void printNumbers(double[] doubleNumbers)
{
foreach (double element in doubleNumbers)
{
Console.WriteLine(element);
}
}
Generic method which help to have one method for both of the above
private static void printNumbers<E>(E [] Numbers)
{
foreach (E element in Numbers)
{
Console.WriteLine(element);
}
}
Don't know if this is a secret per se but I loved the added Enumerable (adds to IEnumerable) class in System.Linq.
http://msdn.microsoft.com/en-us/library/system.linq.enumerable_members.aspx
While the yield keyword is already listed. Iterator blocks are freaking amazing. I used them to build Lists that would be tested to see if they were co-prime. It basically allows you to go though a function that returns values one by one and stop any time.
Oh, I almost forgot the best class in the world when you can't optimize it any more. The BackgroundWorker!!!!
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
With reference to the post w/ perma link " Hidden Features of C#? [1]", there is another way to accomplish the same - indentation / line breaks. Check this out..
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.NewLineOnAttributes = true;
xmlWriterSettings.Indent = true;
XmlWriter xml = XmlWriter.Create(@"C:\file.xml", xmlWriterSettings);
// Start writing the data using xml.WriteStartElement(), xml.WriteElementString(...), xml.WriteEndElement() etc
I am not sure whether this is an unknown feature though!
[1] https://stackoverflow.com/questions/9033/hidden-features-of-c/2495330#2495330Lately I learned about the String.Join method. It is really useful when building strings like columns to select by a query.
I think if you have to use nullable types, it's better to use Nullable<.T> rather than the question mark notation. It makes it eye-achingly obvious that magic is occurring. Not sure why anyone would ever want to use Nullable<.bool> though.
In a VB.NET Web service where the parameter might not be passed through (because the partners request wasn't consistent or reliable), but had to pass validation against the proposed type (Boolean for "if is search request"). Chalk it up to "another demand by management"...
...and yes, I know some people think it's not the right way to do these things, but IsSearchRequest As Nullable(Of Boolean) saved me losing my mind that night!
I must admit that i'm not sure wether this performs better or worse than the normal ASP.NET repeater onItemDatabound cast code, but anyway here's my 5 cent.
MyObject obj = e.Item.DataItem as MyObject;
if(obj != null)
{
//Do work
}
PreviousPage property:
"The System.Web.UI.Page representing the page that transferred control to the current page."
It is very useful.
@ Robbie Rocketpants [1]
"but my instincts tell me that this would cut a maximum of two type casts operations down to a maximum of one."
If you do the cast as you were suggesting in example 1 (using is & as), it results in 2 calls to the "is" operator. Because when you do "c = obj as MyClass", first it calls "is" behind the scenes, then if it fails that it simply returns null.
If you do the cast as you were suggesting in example 2,
c = (MyClass)obj
Then this actually performs the "is" operation again, then if it fails that check,it throws an exception (InvalidCastException).
So, if you wanted to do a lightweight dynamic cast, it's best to do the 3rd example you provided:
MyClass c;
if (obj is MyClass)
{
c = obj as MyClass
}
if (c != null)
{
}
vs
MyClass c = obj as MyClass;
if (c != null)
{
}
You can see which is quicker, more consise and clearer.
[1] https://stackoverflow.com/questions/9033?#9092Saw a mention of List.ForEach above; 2.0 introduced a bevy of predicate-based collection operations - Find, FindAll, Exists, etc. Coupled with anonymous delegates you can almost achieve the simplicity of 3.5's lambda expressions.
Some concurrency utilities in the BCL might qualify as hidden features.
Things like System.Threading.Monitor are used internally by the lock keyword; clearly in C# the lock keyword is preferrable, but sometimes it pays to know how things are done at a lower level; I had to lock in C++/CLI, so I encased a block of code with calls to Monitor.Enter() and Monitor.Exit().
Before lambda comes into play, it's anonymous delegate. That could be used for blanket code similar to Ruby's blockgiven. I haven't tested how lambda works though because I want to stick with .NET 2.0 so far.
For example when you want to make sure you remember to close your HTML tags:
MyHtmlWriter writer=new MyHtmlWriter();
writer.writeTag("html",
delegate ()
{
writer.writeTag("head",
delegate()
{
writer.writeTag("title"...);
}
)
})
I am sure if lambda is an option, that could yield much cleaner code :)
In dealing with interop between C++ and C#, many people don't realize that C++/CLI is a great option.
Say you have a C++ DLL and a C# DLL which depends on the C++ DLL. Often, the easiest technique is to compile some (or all) modules of the C++ DLL with the /clr switch. To have the C# call the C++ DLL is to write managed C++ wrapper classes in the C++ DLL. The C++/CLI classes can call the native C++ code much more seamlessly than C#, because the C++ compiler will automatically generate P/invokes for you, has a library specifically for interop, plus language features for interop like pin_ptr [1]. And it allows managed and native code to coexist within the same binary.
On the C# side, you just call into the DLL as you would any other .NET binary.
[1] http://msdn.microsoft.com/en-us/library/1dz8byfh(VS.80).aspxRelection is so powerfull when used carefully. I used it in an e-mail templating system. The template manager would be passed an object and the html templates would have embedded fields that referred to Properties that could be retrieved off the passed object using reflection. Worked out very nicely.
Not sure Microsoft would like this question, especially with so many responses. I'm sure I once heard a Microsoft head say:
a hidden feature is a wasted feature
... or something to that effect.
Use of @ before a string that contains escape char. Basically when a physical path is used to assign in a string variable everybody uses '\' where escape character is present in a string.
e.g. string strPath="D:\websites\web1\images\";
But escape characters can be ignored using @ before the string value.
e.g. string strPath=@"D:\websites\web1\images\";
Another way of geting IEnumerable through yield without explicity creating an IEnumerable object
public IEnumerable<Request> SomeMethod(IEnumerable<Request> requests)
{
foreach (Request request in requests)
yield return DoSomthing(request);
}
requests.Select(DoSomthing)
10 out of 10 times. (Also, edited the sample to fix code errors) - sehe
This trick for calling private methods using Delegate.CreateDelegate [1] is extremely neat.
var subject = new Subject();
var doSomething = (Func<String, String>)
Delegate.CreateDelegate(typeof(Func<String, String>), subject, "DoSomething");
Console.WriteLine(doSomething("Hello Freggles"));
Here's a context where it's useful [2]
[1] http://elegantcode.com/2010/01/28/calling-non-public-methods/Most of the P/Invoke [1] stuff is a bit strange.
Example of attributes:
[DllImport ("gdi32.dll")]
[return : MarshalAs(UnmanagedType.I4)]
[StructLayout(LayoutKind.Sequential)]
[1] http://en.wikipedia.org/wiki/Platform_Invocation_ServicesIf 3rd-party extensions are allowed, then C5 [1] and Microsoft CCR [2] (see this blog post [3] for a quick introduction) are a must-know.
C5 complements .Net's somewhat lacking collections library (not Set???), and CCR makes concurrent programming easier (I hear it's due to be merged with Parallel Extensions).
[1] http://www.google.co.il/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fwww.itu.dk%2Fresearch%2Fc5%2F&ei=H_vTSPmZGZyw0gTK4t2VDQ&usg=AFQjCNEd1FXV-4rROqtPwZ_jDwmW1w5pFA&sig2=ILE99mEc76cQ6g-iRnPgbQSome ?? weirdness :)
Delegate target =
(target0 = target as CallTargetWithContext0) ??
(target1 = target as CallTargetWithContext1) ??
(target2 = target as CallTargetWithContext2) ??
(target3 = target as CallTargetWithContext3) ??
(target4 = target as CallTargetWithContext4) ??
(target5 = target as CallTargetWithContext5) ??
((Delegate)(targetN = target as CallTargetWithContextN));
Interesting to note the last cast that is needed for some reason. Bug or by design?
Here is a TIP [1] of how you can use #Region directive to document your code.
[1] https://stackoverflow.com/questions/169276/is-the-region-directive-really-useful-in-net#287438Not hidden, but pretty neat. I find this a more succinct substitute for a simple if-then-else that just assigns a value based on a condition.
string result =
i < 2 ? //question
"less than 2" : //answer
i < 5 ? //question
"less than 5": //answer
i < 10 ? //question
"less than 10": //answer
"something else"; //default answer
If you want to prevent the garbage collector from running the finalizer of an object, just use GC.SuppressFinalize(object);
. In a similar vein, GC.KeepAlive(object);
will prevent the garbage collector from collecting that object by referencing it. Not very commonly used, at least in my experience, but nice to know just in case.
Exception Filters [1]. So "hidden" you can't even use them (at least from C#) without a post-compilation patch ;)
[1] http://code.msdn.microsoft.com/ExceptionFilterInjctWhen you need to (a)synchronously communicate between objects about occurance of an event there is special purpose interface called ISynchronizeInvoke.
Quoting MSDN article ( link [1]):
Objects that implement this interface can receive notification that an event has occurred, and they can respond to queries about the event. In this way, clients can ensure that one request has been processed before they submit a subsequent request that depends on completion of the first.
Here is a generic wrapper:
protected void OnEvent<T>(EventHandler<T> eventHandler, T args) where T : EventArgs
{
if (eventHandler == null) return;
foreach (EventHandler<T> singleEvent in eventHandler.GetInvocationList())
{
if (singleEvent.Target != null && singleEvent.Target is ISynchronizeInvoke)
{
var target = (ISynchronizeInvoke)singleEvent.Target;
if (target.InvokeRequired) {
target.BeginInvoke(singleEvent, new object[] { this, args });
continue;
}
}
singleEvent(this, args);
}
}
and here is an example usage:
public event EventHandler<ProgressEventArgs> ProgressChanged;
private void OnProgressChanged(int processed, int total)
{
OnEvent(ProgressChanged, new ProgressEventArgs(processed, total));
}
[1] http://msdn.microsoft.com/en-us/library/system.componentmodel.isynchronizeinvoke.aspxSeparate static fields depending on the generic type of the surrounding class.
public class StaticConstrucEx2Outer<T> {
// Will hold a different value depending on the specicified generic type
public T SomeProperty { get; set; }
static StaticConstrucEx2Outer() {
Console.WriteLine("StaticConstrucEx2Outer " + typeof(T).Name);
}
public class StaticConstrucEx2Inner<U, V> {
static StaticConstrucEx2Inner() {
Console.WriteLine("Outer <{0}> : Inner <{1}><{2}>",
typeof(T).Name,
typeof(U).Name,
typeof(V).Name);
}
public static void FooBar() {}
}
public class SCInner {
static SCInner() {
Console.WriteLine("SCInner init <{0}>", typeof(T).Name);
}
public static void FooBar() {}
}
}
StaticConstrucEx2Outer<int>.StaticConstrucEx2Inner<string, DateTime>.FooBar();
StaticConstrucEx2Outer<int>.SCInner.FooBar();
StaticConstrucEx2Outer<string>.StaticConstrucEx2Inner<string, DateTime>.FooBar();
StaticConstrucEx2Outer<string>.SCInner.FooBar();
StaticConstrucEx2Outer<string>.StaticConstrucEx2Inner<string, Int16>.FooBar();
StaticConstrucEx2Outer<string>.SCInner.FooBar();
StaticConstrucEx2Outer<string>.StaticConstrucEx2Inner<string, UInt32>.FooBar();
StaticConstrucEx2Outer<long>.StaticConstrucEx2Inner<string, UInt32>.FooBar();
Will produce the following output
Outer <Int32> : Inner <String><DateTime>
SCInner init <Int32>
Outer <String> : Inner <String><DateTime>
SCInner init <String>
Outer <String> : Inner <String><Int16>
Outer <String> : Inner <String><UInt32>
Outer <Int64> : Inner <String><UInt32>
I don't know if this is a hidden feature (""). Any string function.
Currying using
FastFunc<T,U>
"a".Equals("A", StringComparison.OrdinalIgnoreCase)
- SLaks