Avoidable boxing in string interpolation - c#

Using string interpolation makes my string format looks much more clear, however I have to add .ToString() calls if my data is a value type.
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
var person = new Person { Name = "Tom", Age = 10 };
var displayText = $"Name: {person.Name}, Age: {person.Age.ToString()}";
The .ToString() makes the format longer and uglier. I tried to get rid of it, but string.Format is a built-in static method and I can't inject it. Do you have any ideas about this? And since string interpolation is a syntax sugar of string.Format, why don't they add .ToString() calls when generating the code behind the syntax sugar? I think it's doable.

I do not see how you can avoid that boxing by compiler. Behavior of string.Format is not part of C# specification. You can not rely on that it will call Object.ToString(). In fact it does not:
using System;
public static class Test {
public struct ValueType : IFormattable {
public override string ToString() => "Object.ToString";
public string ToString(string format, IFormatProvider formatProvider) => "IFormattable.ToString";
}
public static void Main() {
ValueType vt = new ValueType();
Console.WriteLine($"{vt}");
Console.WriteLine($"{vt.ToString()}");
}
}

With the recent release of C# 10 and .NET 6 things changed. The compiler has been optimised to handle interpolated strings better. What I write here I took from a post by Stephen Toub.
In essence: earlier versions of .NET translated an interpolated string $"{major}.{minor}.{build}.{revision}" (with the variables all being integers) into something like this
var array = new object[4];
array[0] = major;
array[1] = minor;
array[2] = build;
array[3] = revision;
string.Format("{0}.{1}.{2}.{3}", array);
Since C#10 the compiler can use "interpolated string handlers". The above string can be translated into:
var handler = new DefaultInterpolatedStringHandler(literalLength: 3, formattedCount: 4);
handler.AppendFormatted(major);
handler.AppendLiteral(".");
handler.AppendFormatted(minor);
handler.AppendLiteral(".");
handler.AppendFormatted(build);
handler.AppendLiteral(".");
handler.AppendFormatted(revision);
return handler.ToStringAndClear();
According to the author that does not only remove the need for boxing, it introduces further enhancements. As a result the new approach achieves "40% throughput improvement and an almost 5x reduction in memory allocation" (Stephen Toub).
And this is only the tip of the iceberg. Besides interpolated string handlers further optimisations in the interpretation of interpolated strings were introduced to C#10.
So I stopped worrying too much about performance and focus on clarity and readability instead. Chances are that we spend a lot of time trying to outsmart the compiler at the cost of code clarity without achieving anything substantial. I'd say, unless we have serious performance issues, we can use interpolated strings without taking complicated detours.
Limitation. Situation may be different when we translate strings. Then our format string becomes a dynamic resource, right? Now the compiler is unable to interpret the string before runtime and we're back to string.Format again.

Related

Use Delegate C#

I am new to delegates , I would like to know the diference between the first code and second code
I have a class
public class FindPerson
{
public int Age;
public string Name;
public string Surname;
public FindPerson(string name, string surname, int age)
{
this.Age = age;
this.Surname = surname;
this.Name = name;
}
public override string ToString()
{
return "Name=" + this.Name + " Surname=" + this.Surname + ", Age=" + this.Age.ToString();
}
}
First code
public void Test2()
{
List<FindPerson> lst = new List<FindPerson>();
lst.Add(new FindPerson("Alex","Sweit",31));
lst.Add(new FindPerson("Alex2", "Sweit", 30));
lst.Add(new FindPerson("Alex3", "Sweit", 34));
FindPerson iam = lst.Find(a => a.Name.Equals("Alex"));
}
Second code:
public void Test2()
{
List<FindPerson> lst = new List<FindPerson>();
lst.Add(new FindPerson("Alex","Sweit",31));
lst.Add(new FindPerson("Alex2", "Sweit", 30));
lst.Add(new FindPerson("Alex3", "Sweit", 34));
FindPerson iam2 = lst.Find(new Predicate<FindPerson>(delegate(FindPerson find)
{
return find.Name.Equals("Alex");
}));
}
I am learning to use delegates but it is not clear.
It's essentially the same thing.
The delegate() { } syntax was introduced in C# 2.0, while the lambda syntax was introduced in C# 3.0. They were designed with different goals in mind, but serve the same purpose.
Let me quote Eric Lippert (it's #7 on his top 10 worst C# features):
I think all concerned would agree that it's unfortunate to have two inconsistent syntaxes for what is basically the same thing. C# is stuck with it, though, because existing C# 2.0 code still uses the old syntax.
The "heaviness" of the C# 2.0 syntax was seen at the time as a benefit. The thought was that users might be confused by this new feature of nested methods, and the design team wanted a clear keyword in there calling out that a nested method was being converted to a delegate. No one could see into the future to know that a much lighter-weight syntax would be needed in a couple of years.
You won't see the delegate() { } syntax being used much in new code nowadays, as virtually everyone prefers the lighter lambda => syntax.
new Predicate<FindPerson> just types the delegate explicitly and isn't needed anymore. It used to be mandatory in C# 1 IIRC. It can be inferred in most cases so it can be omitted (see here for an example case when it's needed).
Its existence is due to the fact that a lambda is represented by a class instance under the hood, and in this particular case Predicate<T> is that class. A "raw" lambda is untyped per se, but it can be implicitly converted to any compatible delegate type.
For instance, Predicate<FindPerson> is a compatible delegate type in this example, but so is Func<FindPerson, bool>. The same lambda would also be convertible to Expression<Func<FindPerson, bool>>, but this is an entirely different matter. This is why you can't write var fn = (int x) => x; in C#, as
the type of fn cannot be inferred from this expression alone.
As a recap, these are all equivalents:
// Compact lambda
lst.Find(a => a.Name.Equals("Alex"))
// Explicitly typed parameter
lst.Find((FindPerson a) => a.Name.Equals("Alex"))
// Explicit delegate type
lst.Find(new Predicate<FindPerson>(a => a.Name.Equals("Alex")))
// Combination of the two above
lst.Find(new Predicate<FindPerson>((FindPerson a) => a.Name.Equals("Alex")))
// Explicit delegate type through casting
lst.Find((Predicate<FindPerson>)(a => a.Name.Equals("Alex")))
// Lambda block
lst.Find(a => { return a.Name.Equals("Alex"); })
// Delegate block
lst.Find((Predicate<FindPerson>)(delegate(FindPerson a) { return a.Name.Equals("Alex"); }))
// ... etc
The first example uses what's called a "lambda" expression (introduced in .Net 3.5) which is a simpler, more succinct (and I think) more elegant way to express anonymous delegates. The second code is the older, more verbose way of doing the same thing.
They are identical in terms of the IL code generated. The first one is a lot nicer to read and write, though - and is generally more common. Delegates are very rarely used nowadays.
There is no difference except for syntax. Find method expects Predicate<T> as an argument, and it's on you to decide weather you are gonna create it on your own with new keyword, or pass a lambda expression and let compiler do that for you.

String - Difference between Clone, Copy, and Standard Affectation

I've just come across a block like this while browsing through legacy code :
object exeName = _connectionSettings.ApplicationName.Clone();
RandomFunction(exeName);
It seemed useless to me at first, but it made me wonder. Is there a fundamental difference between:
var copiedString = initialString;
var copiedString = initialString.Clone();
var copiedString = string.Copy(initialString);
I've created a basic unit test that seems to show there is none since it behaves the same way regardless of the method used (initial affectation of copiedString, change of the initialString, assertion of copiedString value) . Am I missing something?
Using Reflector to look at the implementation of String.Clone() reveals this:
public object Clone()
{
return this;
}
So the answer is "No, there is no difference between assigning and cloning for a string".
However, Copy() is somewhat different:
public static unsafe string Copy(string str)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
int length = str.Length;
string str2 = FastAllocateString(length);
fixed (char* chRef = &str2.m_firstChar)
{
fixed (char* chRef2 = &str.m_firstChar)
{
wstrcpy(chRef, chRef2, length);
}
}
return str2;
}
This is actually making a copy - but since strings are immutable, it's not very useful anyway.
But - and this is important - Copy() will return a DIFFERENT REFERENCE from the original string, and Clone() will return the SAME REFERENCE as the original string.
Another thing to be aware of is string interning which causes strings with identical values to share the data (and therefore have the same string reference).
For example, the following code will print "Same!":
string s1 = "Hello";
string s2 = "Hello";
if (ReferenceEquals(s1, s2))
Console.WriteLine("Same!");
But the following code will print "Not same!", even though the string values are the same:
string s1 = "Hello";
string s2 = "He";
string s3 = "llo";
string s4 = s2 + s3;
if (!ReferenceEquals(s1, s4))
Console.WriteLine("Not Same!");
We can explicitly intern s4, so that the following prints "Same!":
string s1 = "Hello";
string s2 = "He";
string s3 = "llo";
string s4 = s2 + s3;
s4 = string.Intern(s4);
if (ReferenceEquals(s1, s4))
Console.WriteLine("Same!");
String.Clone() does nothing but return the reference to the same string (see here)
But since strings in C# are immutable anyway, there's no difference between all three methods you've specified.
Since the CLR implements immutable strings, and treats strings like values, semantically, the only time it would ever be an issue in correct code is outside of the managed code sandbox.
In context of managed code, strings should be simply assigned, just like int and byte and float.
Since the CLR implements immutable strings, and treats strings like values, semantically, the only time it would ever be an issue in correct code is outside of the managed code sandbox, and even so, correct code would properly consider all aspects of CLR strings (as in 2 strings may refer to the same "value").
In context of managed code, strings should be simply assigned, just like int and byte and float.

ToString method and return static string

Class example:
public class SomeType
{
private int type;
// some code...
public override string ToString ()
{
if (type == 1) return "One";
if (type == 2) return "Two";
}
}
Now imagine application calls thousand times ToString() method in a second.
My question is: when I use inline created string in code like something = myClass.ToString() is in every call created a new string or compiler optimize it somehow? (because strings are immutable it could be returned only referense to a static string).
And if not, should I make static private string fields and return them in ToString method for performance reasons?
Ofcourse I will test it using Stopwatch, but I need an expert answer anyway.
You're using string literals - which means you're returning a reference to the same string each time. This is guaranteed by the language specification. From section 2.4.4.5 of the C# 5 specification:
When two or more string literals that are equivalent according to the string equality operator (§7.10.7) appear in the same program, these string literals refer to the same string instance.
So as a simpler example:
string x = "One";
string y = "One";
Console.WriteLine(object.ReferenceEquals(x, y)); // Prints True
In your code, the ToString() method will still be called - but it won't create a new string object each time. You might consider using a switch statement instead of all those if statements, by the way.
Note that even if it did create a new string each time, creating thousands of strings per second won't make a modern CPU break into a sweat. Both the allocator and garbage collector are pretty efficient, and modern computers can do an awful lot of work in a second.

What is the smoothest, most appealing syntax you've found for asserting parameter correctness in c#?

A common problem in any language is to assert that parameters sent in to a method meet your requirements, and if they don't, to send nice, informative error messages. This kind of code gets repeated over and over, and we often try to create helpers for it. However, in C#, it seems those helpers are forced to deal with some duplication forced upon us by the language and compiler. To show what I mean, let me present some some raw code with no helpers, followed by one possible helper. Then, I'll point out the duplication in the helper and phrase my question precisely.
First, the code without any helpers:
public void SomeMethod(string firstName, string lastName, int age)
{
if(firstName == null)
{
throw new WhateverException("The value for firstName cannot be null.");
}
if(lastName == null)
{
throw new WhateverException("The value for lastName cannot be null.");
}
// Same kind of code for age, making sure it is a reasonable range (< 150, for example).
// You get the idea
}
}
Now, the code with a reasonable attempt at a helper:
public void SomeMethod(string firstName, string lastName, int age)
{
Helper.Validate( x=> x !=null, "firstName", firstName);
Helper.Validate( x=> x!= null, "lastName", lastName);
}
The main question is this: Notice how the code has to pass the value of the parameter and the name of the parameter ("firstName" and firstName). This is so the error message can say, "Blah blah blah the value for the firstName parameter." Have you found any way to get around this using reflection or anything else? Or a way to make it less painful?
And more generally, have you found any other ways to streamline this task of validating parameters while reducing code duplication?
EDIT: I've read people talking about making use of the Parameters property, but never quite found a way around the duplication. Anyone have luck with that?
Thanks!
You should check out Code Contracts; they do pretty much exactly what you're asking. Example:
[Pure]
public static double GetDistance(Point p1, Point p2)
{
CodeContract.RequiresAlways(p1 != null);
CodeContract.RequiresAlways(p2 != null);
// ...
}
Wow, I found something really interesting here. Chris above gave a link to another Stack Overflow question. One of the answers there pointed to a blog post which describes how to get code like this:
public static void Copy<T>(T[] dst, long dstOffset, T[] src, long srcOffset, long length)
{
Validate.Begin()
.IsNotNull(dst, “dst”)
.IsNotNull(src, “src”)
.Check()
.IsPositive(length)
.IsIndexInRange(dst, dstOffset, “dstOffset”)
.IsIndexInRange(dst, dstOffset + length, “dstOffset + length”)
.IsIndexInRange(src, srcOffset, “srcOffset”)
.IsIndexInRange(src, srcOffset + length, “srcOffset + length”)
.Check();
for (int di = dstOffset; di < dstOffset + length; ++di)
dst[di] = src[di - dstOffset + srcOffset];
}
I'm not convinced it is the best answer yet, but it certainly is interesting. Here's the blog post, from Rick Brewster.
This may be somewhat helpful:
Design by contract/C# 4.0/avoiding ArgumentNullException
I tackled this exact problem a few weeks ago, after thinking that it is strange how testing libraries seem to need a million different versions of Assert to make their messages descriptive.
Here's my solution.
Brief summary - given this bit of code:
int x = 3;
string t = "hi";
Assert(() => 5*x + (2 / t.Length) < 99);
My Assert function can print out the following summary of what is passed to it:
(((5 * x) + (2 / t.Length)) < 99) == True where
{
((5 * x) + (2 / t.Length)) == 16 where
{
(5 * x) == 15 where
{
x == 3
}
(2 / t.Length) == 1 where
{
t.Length == 2 where
{
t == "hi"
}
}
}
}
So all the identifier names and values, and the structure of the expression, could be included in the exception message, without you having to restate them in quoted strings.
Alright guys, it's me again, and I found something else that is astonishing and delightful. It is yet another blog post referred to from the other SO question that Chris, above, mentioned.
This guy's approach lets you write this:
public class WebServer
{
public void BootstrapServer( int port, string rootDirectory, string serverName )
{
Guard.IsNotNull( () => rootDirectory );
Guard.IsNotNull( () => serverName );
// Bootstrap the server
}
}
Note that there is no string containing "rootDirectory" and no string containing "serverName"!! And yet his error messages can say something like "The rootDirectory parameter must not be null."
This is exactly what I wanted and more than I hoped for. Here's the link to the guy's blog post.
And the implementation is pretty simple, as follows:
public static class Guard
{
public static void IsNotNull<T>(Expression<Func<T>> expr)
{
// expression value != default of T
if (!expr.Compile()().Equals(default(T)))
return;
var param = (MemberExpression) expr.Body;
throw new ArgumentNullException(param.Member.Name);
}
}
Note that this makes use of "static reflection", so in a tight loop or something, you might want to use Rick Brewster's approach above.
As soon as I post this I'm gonna vote up Chris, and the response to the other SO question. This is some good stuff!!!
Using my library The Helper Trinity:
public void SomeMethod(string firstName, string lastName, int age)
{
firstName.AssertNotNull("firstName");
lastName.AssertNotNull("lastName");
...
}
Also supports asserting that enumeration parameters are correct, collections and their contents are non-null, string parameters are non-empty etcetera. See the user documentation here for detailed examples.
Here's my answer to the problem. I call it "Guard Claws". It uses the IL parser from the Lokad Shared Libs but has a more straightforward approach to stating the actual guard clauses:
string test = null;
Claws.NotNull(() => test);
You can see more examples of it's usage in the specs.
Since it uses real lambdas as input and uses the IL Parser only to generate the exception in the case of a violation it should perform better on the "happy path" than the Expression based designs elsewhere in these answers.
The links are not working, here is the URL:
http://github.com/littlebits/guard_claws/
The Lokad Shared Libraries also have an IL parsing based implementation of this which avoids having to duplicate the parameter name in a string.
For example:
Enforce.Arguments(() => controller, () => viewManager,() => workspace);
Will throw an exception with the appropriate parameter name if any of the listed arguments is null. It also has a really neat policy based rules implementation.
e.g.
Enforce.Argument(() => username, StringIs.Limited(3, 64), StringIs.ValidEmail);
My preference would be to just evaluate the condition and pass the result rather than passing an expression to be evaluated and the parameter on which to evaluate it. Also, I prefer to have the ability to customize the entire message. Note that these are simply preferences -- I'm not saying that your sample is wrong -- but there are some cases where this is very useful.
Helper.Validate( firstName != null || !string.IsNullOrEmpty(directoryID),
"The value for firstName cannot be null if a directory ID is not supplied." );
Don't know if this technique transfers from C/C++ to C#, but I've done this with macros:
#define CHECK_NULL(x) { (x) != NULL || \
fprintf(stderr, "The value of %s in %s, line %d is null.\n", \
#x, __FILENAME__, __LINE__); }
In this case, rather than use your own exception type, or really general types like ApplicationException.. I think it is best to use the built in exception types that are specifically intended for this use:
Among those.. System.ArgumentException, System.ArgumentNullException...
Postsharp or some other AOP framework.
It does not apply everywhere, but it might help in many cases:
I suppose that "SomeMethod" is carrying out some behavioral operation on the data "last name", "first name" and "age". Evaluate your current code design. If the three pieces of data are crying for a class, put them into a class. In that class you can also put your checks. This would free "SomeMethod" from input checking.
The end result would be something like this:
public void SomeMethod(Person person)
{
person.CheckInvariants();
// code here ...
}
The call would be something like this (if you use .NET 3.5):
SomeMethod(new Person { FirstName = "Joe", LastName = "White", Age = 12 });
under the assumption that the class would look like this:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public void CheckInvariants()
{
assertNotNull(FirstName, "first name");
assertNotNull(LastName, "last name");
}
// here are your checks ...
private void assertNotNull(string input, string hint)
{
if (input == null)
{
string message = string.Format("The given {0} is null.", hint);
throw new ApplicationException(message);
}
}
Instead of the syntactic sugar of .NET 3.5 you can also use constructor arguments to create a Person object.
Just as a contrast, this post by Miško Hevery on the Google Testing Blog argues that this kind of parameter checking might not always be a good thing. The resulting debate in the comments also raises some interesting points.

Hidden Features of C#? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
This came to my mind after I learned the following from this question:
where T : struct
We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.
Some of us even mastered the stuff like Generics, anonymous types, lambdas, LINQ, ...
But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?
Here are the revealed features so far:
Keywords
yield by Michael Stum
var by Michael Stum
using() statement by kokos
readonly by kokos
as by Mike Stone
as / is by Ed Swangren
as / is (improved) by Rocketpants
default by deathofrats
global:: by pzycoman
using() blocks by AlexCuse
volatile by Jakub Šturc
extern alias by Jakub Šturc
Attributes
DefaultValueAttribute by Michael Stum
ObsoleteAttribute by DannySmurf
DebuggerDisplayAttribute by Stu
DebuggerBrowsable and DebuggerStepThrough by bdukes
ThreadStaticAttribute by marxidad
FlagsAttribute by Martin Clarke
ConditionalAttribute by AndrewBurns
Syntax
?? (coalesce nulls) operator by kokos
Number flaggings by Nick Berardi
where T:new by Lars Mæhlum
Implicit generics by Keith
One-parameter lambdas by Keith
Auto properties by Keith
Namespace aliases by Keith
Verbatim string literals with # by Patrick
enum values by lfoust
#variablenames by marxidad
event operators by marxidad
Format string brackets by Portman
Property accessor accessibility modifiers by xanadont
Conditional (ternary) operator (?:) by JasonS
checked and unchecked operators by Binoj Antony
implicit and explicit operators by Flory
Language Features
Nullable types by Brad Barker
Anonymous types by Keith
__makeref __reftype __refvalue by Judah Himango
Object initializers by lomaxx
Format strings by David in Dakota
Extension Methods by marxidad
partial methods by Jon Erickson
Preprocessor directives by John Asbeck
DEBUG pre-processor directive by Robert Durgin
Operator overloading by SefBkn
Type inferrence by chakrit
Boolean operators taken to next level by Rob Gough
Pass value-type variable as interface without boxing by Roman Boiko
Programmatically determine declared variable type by Roman Boiko
Static Constructors by Chris
Easier-on-the-eyes / condensed ORM-mapping using LINQ by roosteronacid
__arglist by Zac Bowling
Visual Studio Features
Select block of text in editor by Himadri
Snippets by DannySmurf
Framework
TransactionScope by KiwiBastard
DependantTransaction by KiwiBastard
Nullable<T> by IainMH
Mutex by Diago
System.IO.Path by ageektrapped
WeakReference by Juan Manuel
Methods and Properties
String.IsNullOrEmpty() method by KiwiBastard
List.ForEach() method by KiwiBastard
BeginInvoke(), EndInvoke() methods by Will Dean
Nullable<T>.HasValue and Nullable<T>.Value properties by Rismo
GetValueOrDefault method by John Sheehan
Tips & Tricks
Nice method for event handlers by Andreas H.R. Nilsson
Uppercase comparisons by John
Access anonymous types without reflection by dp
A quick way to lazily instantiate collection properties by Will
JavaScript-like anonymous inline-functions by roosteronacid
Other
netmodules by kokos
LINQBridge by Duncan Smart
Parallel Extensions by Joel Coehoorn
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:
You can chain the ?? operator so that you can do a bunch of null comparisons.
string result = value1 ?? value2 ?? value3 ?? String.Empty;
Aliased generics:
using ASimpleName = Dictionary<string, Dictionary<string, List<string>>>;
It allows you to use ASimpleName, instead of Dictionary<string, Dictionary<string, List<string>>>.
Use it when you would use the same generic big long complex thing in a lot of places.
From CLR via C#:
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.
My favorite trick is using the null coalesce operator and parentheses to automagically instantiate collections for me.
private IList<Foo> _foo;
public IList<Foo> ListOfFoo
{ get { return _foo ?? (_foo = new List<Foo>()); } }
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 and this blog post by Eric Lippert on this topic (and possible downsides).
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();
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()}
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. Saves you years.
The # tells the compiler to ignore any
escape characters in a string.
Just wanted to clarify this one... it doesn't tell it to ignore the escape characters, it actually tells the compiler to interpret the string as a literal.
If you have
string s = #"cat
dog
fish"
it will actually print out as (note that it even includes the whitespace used for indentation):
cat
dog
fish
I think one of the most under-appreciated and lesser-known features of C# (.NET 3.5) are Expression Trees, 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.
"yield" would come to my mind. Some of the attributes like [DefaultValue()] are also among my favorites.
The "var" 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 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)
I 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 link for more details
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 -- 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.
Unions (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();
If you want to exit your program without calling any finally blocks or finalizers use FailFast:
Environment.FailFast()
Returning anonymous types from a method and accessing members without reflection.
// Useful? probably not.
private void foo()
{
var user = AnonCast(GetUserTuple(), new { Name = default(string), Badges = default(int) });
Console.WriteLine("Name: {0} Badges: {1}", user.Name, user.Badges);
}
object GetUserTuple()
{
return new { Name = "dp", Badges = 5 };
}
// Using the magic of Type Inference...
static T AnonCast<T>(object obj, T t)
{
return (T) obj;
}
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?
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.
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"
?? - coalescing operator
using (statement / directive) - great keyword that can be used for more than just calling Dispose
readonly - should be used more
netmodules - too bad there's no support in Visual Studio
#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.
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;

Categories