TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
C# Tips & Tricks
Gul Md Ershad
Dec 02, 2014
129.4k
0
8
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Print
Other Artcile
This article provides various tips for the C# Language.
When normalizing strings, it is highly recommended that you use ToUpperInvariant instead of ToLowerInvariant because Microsoft has optimized the code for doing uppercase comparisons.
Reference Book:
(CLR via C#, Second Edition (Developer Reference)).
Don't use ToUpper () to do a comparison of a case sensitive string.
When you "convert a string to upper case" you create a second temporary string object. So, use:
String.Equals(stringA, stringB, StringComparison.CurrentCultureIgnoreCase)
Converting to uppercase rather than lowercase can also prevent incorrect behavior in certain cultures. For example, in Turkish, two lowercase i's map to the same uppercase I. Google "Turkish i" for more details.
I (English) – Ben (Turkish)
I (English) – I (Turkish)
Null coalescing operator
It is a binary operator that is the part of basic conditional expression. In C# the null Coalescing operator is ?.
Example:
string
pageTitle = suppliedTitle ??
"Default Title"
;
My favorite trick is using the null coalesce operator and parentheses to automatically instantiate collections for me.
Example
private
IList<Foo> _foo;
public
IList<Foo> ListOfFoo
{
get
{
return
_foo ?? (_foo =
new
List<Foo>());
}
}
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 InvalidCastException exception.
You can collapse your code down even further:
Employee emp =
new
Employee();
emp.Name =
"John Smith"
;
emp.StartDate = DateTime.Now();
Now, use:
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 and so on.
Verbatim string
A String can be created as a verbatim string. Verbatim strings start with the @ symbol. The C# compiler understand this type of string as verbatim. Basically the @ symbol tells the string constructor to ignore escape characters and line breaks.
Example
String Str1 = "";
Str1 = "\\MyServer\TestFolder\NewFolder";
In the statement above, the compiler gives an error of "Unrecognized escape sequence", but if we write the code like this:
str2 = @"\\MyServer\TestFolder\NewFolder";
Using @ for variable names that are keywords.
var @object = new object();
var @string = "";
var @if = IpsoFacto();
Extension Method
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.
The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable<T> types.
Example
class
ExtensionMethods2
{
static
void
Main()
{
int
[] ints = { 10, 45, 15, 39, 21, 26 };
var result = ints.OrderBy(g => g);
foreach
(var i
in
result)
{
System.Console.Write(i +
" "
);
}
}
}
//Output: 10 15 21 26 39 45
Anonymous types can infer property names from the variable name:
string
hello =
"world"
;
var o =
new
{ hello };
Console.WriteLine(o.hello);
Dictionary.TryGetValue(K key, out V value):
if
(dictionary.ContainsKey(key))
{
value = dictionary[key];
}
You can just do:
if
(dictionary.TryGetValue(key,
out
value))
{ ... }
Another benefit of TryGetValue is that if your dictionary is synchronized, there is no race condition.
Use "throw;" instead of "throw ex;" to preserve stack trace
If re-throw an exception without adding additional information, use "throw" instead of "throw ex". An empty "throw" statement in a catch block will emit a 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.
Object.Equals Method
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)))
{
...
}
It can be implemented like the following in one line of code:
if
(Object.Equals(x, y))
{ }
Falling through switch-cases can be done by having no code in a case:
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
;
}
Nested classes can access private members of an outer class.
To test if an IEnumerable<T> is empty with LINQ, use:
IEnumerable<T>.Any();
At first, I was using (IEnumerable<T>.Count() != 0) ...
That unnecessarily causes all items in the IEnumerable<T> to be enumerated.
As an improvement to this, I went on to use (IEnumerable<T>.FirstOrDefault() == null) ...
Which is better.
But IEnumerable<T>.Any() is the most succinct and performs the best.
Trailing Comments
Trialing comments are generally written on the same line as code with some tabs to separate them. These are short comments generally used to add information about variables, object declarations and so on.
Example
long
controlcounts;
// Count of the controls in current context
Assignment and Type Check
class
A {...}
class
B : A {...}
class
C: B {...}
Assignments
A a =
new
A();
// static type of a: the type specified in the declaration (here A)
// dynamic type of a: the type of the object in a (here also A)
a =
new
B();
// dynamic type of a is B
a =
new
C();
// dynamic type of a is C
B b = a;
// forbidden; compilation error
Run time type checks
a =
new
C();
if
(a
is
C) ...
// true, if dynamic type of a is C or a subclass; otherwise false
if
(a
is
B) ...
// true
if
(a
is
A) ...
// true, but warning because it makes no sense
a =
null
;
if
(a
is
C) ...
// false: if a== null, a is T always returns false
Cast
A a =
new
C();
a =
null
;
c = (C) a;
// ok ..null can be casted to any reference type
Properties and indexers can also be overridden (virtual, override).
Dynamic Binding
class
A
{
public
virtualvoid WhoAreYou()
{
Console.WriteLine(
"I am an A"
);
}
}
Now:
class
B : A
{
public
overridevoid WhoAreYou()
{
Console.WriteLine(
"I am a B"
);
}
}
Now:
A a =
new
B();a.WhoAreYou();
// "I am a B"
Hiding
Members can be declared as “new” in subclass.
They hide inherited members with the same class.
class
A
{
public
int
x;
public
void
F() {...}
public
virtual
void
G() {...}
}
Now:
class
B : A
{
public
newint x;
public
new
void
F() {...}
public
newvoid G() {...}
}
Now:
B b =
new
B();
b.x = ...;
// // accesses B.x
b.F(); …. b.G();
// CallsB.F and B.G
Dynamic Binding (with Hiding)
class
A
{
public
virtualvoid WhoAreYou() { Console.WriteLine(
"I am an A"
); }
}
class
B : A
{
public
overridevoid WhoAreYou() { Console.WriteLine(
"I am a B"
); }
}
class
C : B
{
public
new
virtualvoid WhoAreYou() { Console.WriteLine(
"I am a C"
); }
}
class
D : C
{
public
overridevoid WhoAreYou() { Console.WriteLine(
"I am a D"
); }
}
Now:
C c =
new
D();
c.WhoAreYou();
// "I am a D"
A a =
new
D();
a.WhoAreYou();
// "I am a B" !!
C#
C# Language
C# tips
C# Tricks
Recommended Free Ebook
Mastering SOLID Principles in C#
Download Now!
Similar Articles