- 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();
- Employee emp = new Employee {Name="John Smith", StartDate=DateTime.Now()}
- The "default" keyword in generic types:
- T t = default(T);
- 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];
- }
- if(dictionary.TryGetValue(key, out value))
- { ... }
- 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)))
- {
- ...
- }
- 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 {...}
- 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
- 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
- Dynamic Binding
- class A
- {
- public virtualvoid WhoAreYou()
- {
- Console.WriteLine("I am an A");
- }
- }
- class B : A
- {
- public overridevoid WhoAreYou()
- {
- Console.WriteLine("I am a B");
- }
- }
- 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() {...}
- }
- class B : A
- {
- public newint x;
- public new void F() {...}
- public newvoid G() {...}
- }
- 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"); }
- }
- C c = new D();
- c.WhoAreYou();// "I am a D"
- A a = new D();
- a.WhoAreYou();// "I am a B" !!
All Types GNIIT/NIIT Solution (Mr Jerry) Follow me on G+ and Twitter for more updates Twitter @mrjerry0001 #Write for us and get paid contact us On hike App:- @mrjerry4968
Pages
- Home
- HTML LAB@HOME
- DSA LAB@HOME
- WCD LAB@HOME
- C# LAB@HOME
- RDBMS LAB@HOME
- IADRT Lab@home
- EBDD LAB@HOME
- ACPC Lab@home
- LBEPS Lab@home
- ICTWC LAB@HOME
- SQL LAB@HOME
- WINDOWS APP LAB@HOME
- JAVA LAB@HOME
- NETWORK ESSENTIALS + LAB@HOME
- ASP.NET LAB@HOME
- LBEPS CYCLE TEST
- ASP.NET CYCLE TEST
- JAVA CYCLE TEST
- RDBMS CYCLE TEST
- DSA CYCLE TEST
- NIIT-HTML CYCLE TEST
- NIIT ASSIGNMENTS
- NIIT PROJECTS
- CORE JAVA NOTES
- NIIT BOOKS
- NIIT MT SOLVED
Friday, 24 June 2016
C# Tips & Tricks
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment