Friday, March 30, 2018

Create custom SQL exception with custom message in C# (CSharp)

Below is a sample code which is used to create a custom SQL exception with custom message. The parameter accepts the message to be thrown. It is mostly used in Unit testing scenario where you need to validate for a custom message.

Sample Code
  1. private SqlException GetSqlException(string message)
  2. {
  3. SqlErrorCollection collection = Construct();
  4. SqlError error = Construct(-2, (byte)2, (byte)3, "Server", message, "Prcedure", 100, (uint)1);
  5. typeof(SqlErrorCollection)
  6. .GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance)
  7. .Invoke(collection, new object[] { error });
  8. var e = typeof(SqlException)
  9. .GetMethod("CreateException", BindingFlags.NonPublic | BindingFlags.Static, null, CallingConventions.ExplicitThis, new[] { typeof(SqlErrorCollection), typeof(string) }, new ParameterModifier[] { })
  10. .Invoke(null, new object[] { collection, "11.0.0" }) as SqlException;
  11. return e;
  12. }
  1. private T Construct(params object[] p)
  2. {
  3. return (T)typeof(T).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0].Invoke(p);
  4. }

Sunday, March 4, 2018

What is the Difference between String and string in C#?

String stands for System.String and it is a .NET Framework type. string is an alias in the C# language for System.String. Both of them are compiled to System.String in IL (Intermediate Language), so there is no difference. At execution time there is no difference. As far as guidelines, it's recommended to use string any time you're referring to an object.

Example:
  1. string place = "Hello World";
It's generally recommended to use String if you need to refer specifically to the class.

Example:
  1. var place = 'World!'
  2. string message = String.Format("Hello {0}!", place);
Similarly for other datatypes,
  1. object:  System.Object
  2. string:  System.String
  3. bool:    System.Boolean
  4. byte:    System.Byte
  5. sbyte:   System.SByte
  6. short:   System.Int16
  7. ushort:  System.UInt16
  8. int:     System.Int32
  9. uint:    System.UInt32
  10. long:    System.Int64
  11. ulong:   System.UInt64
  12. float:   System.Single
  13. double:  System.Double
  14. decimal: System.Decimal
  15. char:    System.Char