C# Tips & Tricks


How to parse a string to target enumeration value?

  1: using System;
  2: namespace Dashing
  3: {
  4:     class EnumParser
  5:     {
  6:         static void Main()
  7:         {
  8:             dynamic month = Enum.Parse(typeof (Month), "Feb");
  9:             Console.WriteLine(month);
 10:         }  // output is: Feb
 11:         enum Month
 12:         {
 13:             Jan,
 14:             Feb,
 15:             March
 16:         }
 17:     }
 18: }

Difference between arguments and parameters

  1: namespace TestOne
  2: {
  3:     class Program
  4:     {
  5:         static void Main()
  6:         {
  7:             const string argument = "Muaz Khan";
  8:             Method(argument);
  9:         }
 10:
 11:         static void Method(string parameter)
 12:         {
 13:             System.Console.WriteLine(parameter);
 14:         }
 15:     }
 16: }

So, the parameter is a variable which is the part of the method, however argument is the variable which invoke in the place of parameter. Arguments initialize parameters.

Optional parameters restrictions

  1. Ref or outmodifiers not allowed.
  2. Paramsarray is not allowed as optional, and must be the last parameter.
  3. Optional parameters must be written after required parameters.
  4. Default value of optional parameter must be a Compile-time constant.

Following code shows example with comments:

  1: using System;
  2: using System.Xml.Linq;
  3:
  4: namespace TestOne
  5: {
  6:     class Program
  7:     {
  8:         void Method(string optional = "Muaz", string required)
  9:         {
 10:             // Error: Optional parameter must appear after all required parameters.
 11:         }
 12:         void MethodTwo(DateTime dateTime = DateTime.Now)
 13:         {
 14:             // default parameter value for DateTime must be a Compile-time Constant
 15:         }
 16:         void MethodThree(XName xName = "default")
 17:         {
 18:             // 'xName' is of type 'XName'. A default parameter of a reference 
 19:             // type other than string can only be initialized with null
 20:         }
 21:         void MethodFour(params string[] names = null)
 22:         {
 23:             // Cannot specify a default value for parameter array.
 24:         }
 25:         void MethodFive(ref string name = "Muaz")
 26:         {
 27:             // A 'ref' or 'out' parameter cannot have a default value
 28:         }
 29:     }
 30: }

Solution of Non-Constant Optional Parameters

  1: using System;
  2:
  3: namespace TestOne
  4: {
  5:     class Program
  6:     {
  7:         static void Main()
  8:         {
  9:             NonConstant();
 10:             Console.ReadLine();
 11:         }
 12:         static void NonConstant(DateTime? dateTime = null)
 13:         {
 14:             Console.WriteLine(dateTime ?? DateTime.Now);
 15:         }
 16:     }
 17: }

Actually, here C# feature nullable type is used to check whether argument supplied is null, if this is the case, put current date.

Optional & Named parameters in Constructor

  1: using System;
  2: namespace TestOne
  3: {
  4:     class Program
  5:     {
  6:         static void Main()
  7:         {
  8:             var myClass = new MyClass(address: "Hazro City", name: "Muaz Khan");
  9:             Console.WriteLine(myClass);
 10:             Console.ReadLine();
 11:         }
 12:     }
 13:     class MyClass
 14:     {
 15:         public string Name { get; set; }
 16:         public string Address { get; set; }
 17:         public string Phone { get; set; }
 18:         public MyClass(string name, string address, string phone = null)
 19:         {
 20:             Name = name;
 21:             Address = address;
 22:             Phone = phone ?? "0307-5272272";
 23:         }
 24:         public override string ToString()
 25:         {
 26:             return string.Format("Name= {0} from {1} and Phone={2}", Name, Address, Phone);
 27:         }
 28:     }
 29: }

Covariance and Contravariance

  1: using System;
  2: namespace TestOne
  3: {
  4:     interface IFactory<out T>  // Covariant
  5:     {
  6:         T CreateInstance(); // values coming out of an API
  7:     }
  8:     interface IPrinter<in T>  // Contravariance
  9:     {
 10:         void Print(T document); // values coming into an API
 11:     }
 12: }

Invariance – the values going both ways

  1: using System;
  2: namespace TestOne
  3: {
  4:     interface IStorage<T>   // Invariance
  5:     {
  6:         byte[] Serialize(T value);   // Contravariance
  7:         T Deserialize(byte[] data);  // Covariance
  8:     }
  9: }

Ref and out – the C# operators

Ref is like Invariance, means values comes to the method as parameter, and back and method return type. However, out operator is like covariance, i.e. values only out from the method, not in.

Covariance and Contravariance in delegates

  1: namespace TestOne
  2: {
  3:     internal delegate T Func<out T>(); // Covariant
  4:     internal delegate void Action<in T>(T value); // contravariant
  5: }

Covariance and Contravariance Limitation:

Only interface and delegates can have variant type parameters (i.e. out/in operators for type parameters in C# 4). In or out modifiers are not applicable to classes.

  1: class VariantLimit<out T>
  2: {
  3:    // Error: Variant type parameters could be declared in 
  4:   // interfaces or delegates only..... !
  5: }

String Extensions =>

  1: public static class StringExtensions
  2:     {
  3:         public static string Truncate(this string s, int maxLength)
  4:         {
  5:             if (string.IsNullOrEmpty(s) || maxLength <= 0)
  6:                 return string.Empty;
  7:             else if (s.Length > maxLength)
  8:                 return s.Substring(0, maxLength) + "...";
  9:             else
 10:                 return s;
 11:         }
 12:
 13:         // IsNumeric Function
 14:         public static bool IsNumeric(this string Expression)
 15:         {
 16:             // Variable to collect the Return value of the TryParse method.
 17:             bool isNum;
 18:   // Define variable to collect out parameter of the TryParse method. If the conversion fails, the out parameter is zero.
 19:             double retNum;
 20:
 21:             // The TryParse method converts a string in a specified style and culture-specific format to its double-precision floating point number equivalent.
 22:             // The TryParse method does not generate an exception if the conversion fails. If the conversion passes, True is returned. If it does not, False is returned.
 23:             isNum = Double.TryParse(Expression, System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
 24:             return isNum;
 25:         }
 26:
 27:     }
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s