├── .gitignore └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # C-sharp-Cheatsheet 2 | A cheat sheet to the C# language/ All-in-One / Still Editing 3 | ![paM5iAD](https://user-images.githubusercontent.com/33767811/60687870-77aa3c00-9ec2-11e9-8db7-a78cd60569eb.jpg) 4 | 5 | - **[String](#String)** 6 | - **[DateTime](#DateTime)** 7 | - **[Exception class](#Complete-List-Of-Exception-Class-In-C#)** 8 | - **[Keywords](#Keywords)** 9 | 10 | ## String 11 | The string is a sequence of characters surrounded with double quotes. A string class in C# is an object of type System.String. The String class in C# represents a string. 12 | String class defined in the .NET base class library represents text as a series of Unicode characters. The String class provides methods and properties to work with strings. 13 | 14 | The String class has methods to clone a string, compare strings, concatenate strings, and copy strings. This class also provides methods to find a substring in a string, find the index of a character or substring, replace characters, split a string, trim a string, and add padding to a string. 15 | The string class also provides methods to convert a string's characters to uppercase or lowercase. 16 | ```csharp 17 | string firstName = "David"; 18 | string lastName = "Mosyan"; 19 | ``` 20 | 21 | ### Concatenating 22 | To concatenate string variables, you can use the 23 | **+** or **+=** operators, **string interpolation** or **the String.Format, String.Concat, String.Join** or **StringBuilder.Append** methods. 24 | The + operator is easy to use and makes for intuitive code. Even if you use several + operators in one statement, the string content is copied only once. 25 | The following code shows examples of using the + and += operators to concatenate strings: 26 | 27 | ```csharp 28 | string fullName = firstName + " " + lastName; // + operator 29 | string fullName = string fullName = string.Format("{0} {1}", firstName, lastName); // .Format method 30 | string fullName = $"My name is {firstName} and my last name is {lastName}."; // Interpolation 31 | 32 | string[] words = { "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog." }; 33 | string unreadablePhrase = string.Concat(words); 34 | Console.WriteLine(unreadablePhrase); //The output is " Thequickbrownfoxjumpsoverthelazydog. " 35 | ``` 36 | Use **String.Join** method if source strings should be separated by a delimeter. 37 | ```csharp 38 | string[] words = { "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog." }; 39 | string readablePhrase = string.Join(" ", words); 40 | Console.WriteLine(readablePhrase); // The output is " The quick brown fox jumps over the lazy dog. " 41 | ``` 42 | In other cases you may be combining strings in a loop, where you don't know how many source strings you are combining, 43 | and the actual number of source strings may be quite large. The **StringBuilder** class was designed for these scenarios. 44 | The following code uses the **Append** method of the **StringBuilder** class to concatenate strings. 45 | 46 | ```csharp 47 | var sb = new System.Text.StringBuilder(); 48 | for (int i = 0; i < 20; i++) 49 | { 50 | sb.AppendLine(i.ToString()); 51 | } 52 | Console.WriteLine(sb.ToString()); 53 | ``` 54 | You can read more about the [reasons to choose string concatenation or the StringBuilder class](https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder?view=netframework-4.8#StringAndSB) 55 | 56 | 57 | ### Common String Methods 58 | #### Returns: 0 - true, 1 - false 59 | | Method | Code | Comments | 60 | | --- | --- | --- | 61 | | Clone() | firstName.Clone() | Make clone of string | 62 | | CompareTo() | firstName.CompareTo(lastname) | Compare two strings and returns integer value as output. It returns 0 for true and 1 for false | 63 | | Contains | firstName.Contains("Dav") | The Contains method checks whether specified character or string is exists or not in the string value | 64 | | EndsWith() | firstName.EndsWith("n") | This EndsWith Method checks whether specified character is the last character of string or not | 65 | | Equals() | firstnName.Equals(lastname) | The Equals Method in C# compares two string and returns Boolean value as output | 66 | | GetHashCode() | firstName.GetHashCode() | This method returns HashValue of specified string | 67 | | GetType() | firstName.GetType() | Returns the System.Type of current instance | 68 | | IndexOf() | firstName.IndexOf("e") | Returns the index position of first occurrence of specified character | 69 | | ToLower() | firstName.ToLower() | Converts String into lower case based on rules of the current culture | 70 | | ToUpper() | firstName.ToUper() | Converts String into upper case based on rules of the current culture | 71 | | Insert() | firstName.Insert(0, "Hello") | Insert the string or character in the string at the specified position | 72 | | IsNormalized() | firstName.IsNormalized() | This method checks whether this string is in Unicode normalization form C | 73 | | LastIndexOf() | firsName.LastIndexOf("e") | This method checks whether this string is in Unicode normalization form C | 74 | | Length | firstName.Length | It is a string property that returns length of string | 75 | | Remove() | firstName.Remove(5) | This method deletes all the characters from beginning to specified index position | 76 | | Replace() | firstName.Replace('e','i') | This method replaces the character | 77 | | Split() | string[] split = firstname.Split(new char[] { 'e' }); | This method splits the string based on specified value | 78 | | StartsWith() | firstName.StartsWith("S") | It checks whether the first character of string is same as specified character | 79 | | Substring() | firstName.Substring(2,5) | This method returns substring | 80 | | ToCharArray() | firstnName.ToCharArray() | Converts string into char array | 81 | | Trim() | firstnName.Trim() | It removes extra whitespaces from beginning and ending of string | 82 | 83 | ### Parsing strings to convert them to DateTime objects 84 | ```csharp 85 | string dateInput = "Jan 1, 2009"; 86 | DateTime parsedDate = DateTime.Parse(dateInput); 87 | Console.WriteLine(parsedDate); 88 | // Displays the following output on a system whose culture is en-US: 89 | // 1/1/2009 12:00:00 AM 90 | ``` 91 | You can read more about Parsing strings to convert them to DateTime objects [here](https://docs.microsoft.com/en-us/dotnet/standard/base-types/parsing-datetime#code-try-0) 92 | 93 | In C#, the string keyword is an alias for [String](https://docs.microsoft.com/en-us/dotnet/api/system.string?view=netframework-4.8). Therefore, String and string are equivalent, and you can use whichever naming convention you prefer. 94 | 95 | ## DateTime 96 | 97 | DateTime is a structure of value Type like int, double etc. It is available in System namespace and present in mscorlib.dll assembly. It implements interfaces like IComparable, IFormattable, IConvertible, ISerializable, IComparable, IEquatable. 98 | ```csharp 99 | public struct DateTime : IComparable, IFormattable, IConvertible, ISerializable, IComparable, IEquatable 100 | { 101 | // Contains methods and properties 102 | } 103 | ``` 104 | DateTime helps developer to find out more information about Date and Time like Get month, day, year, week day. It also helps to find date difference, add number of days to a date, etc. 105 | 106 | ### Standard DateTime Formatting 107 | DateTimeFormatInfo specifies a set of specifiers for simple date and time formatting. Every specifier correspond to 108 | a particular DateTimeFormatInfo format pattern. 109 | ```csarp 110 | //Create datetime 111 | DateTime dt = new DateTime(2016, 08, 01, 18, 50, 23, 230); 112 | var t = String.Format("{0:t}", dt); // "6:50 PM" ShortTime 113 | var d = String.Format("{0:d}", dt); // "8/1/2016" ShortDate 114 | var T = String.Format("{0:T}", dt); // "6:50:23 PM" LongTime 115 | var D = String.Format("{0:D}", dt); // "Monday, August 1, 2016" LongDate 116 | var f = String.Format("{0:f}", dt); // "Monday, August 1, 2016 6:50 PM" LongDate+ShortTime 117 | var F = String.Format("{0:F}", dt); // "Monday, August 1, 2016 6:50:23 PM" FullDateTime 118 | var g = String.Format("{0:g}", dt); // "8/1/2016 6:50 PM" ShortDate+ShortTime 119 | var G = String.Format("{0:G}", dt); // "8/1/2016 6:50:23 PM" ShortDate+LongTime 120 | var m = String.Format("{0:m}", dt); // "August 1" MonthDay 121 | var y = String.Format("{0:y}", dt); // "August 2016" YearMonth 122 | var r = String.Format("{0:r}", dt); // "SMon, 01 Aug 2016 18:50:23 GMT" RFC1123 123 | var s = String.Format("{0:s}", dt); // "2016-08-01T18:50:23" SortableDateTime 124 | var u = String.Format("{0:u}", dt); // "2016-08-01 18:50:23Z" UniversalSortableDateTime 125 | ``` 126 | #### Custom DateTime Formatting 127 | There are following custom format specifiers: 128 | -y (year) 129 | -M (month) 130 | -d (day) 131 | -h (hour 12) 132 | -H (hour 24) 133 | -m (minute) 134 | -s (second) 135 | -f (second fraction) 136 | -F (second fraction, trailing zeroes are trimmed) 137 | -t (P.M or A.M) 138 | -z (time zone) 139 | 140 | ```csharp 141 | var year = String.Format("{0:y yy yyy yyyy}", dt); // "16 16 2016 2016" year 142 | var month = String.Format("{0:M MM MMM MMMM}", dt); // "8 08 Aug August" month 143 | var day = String.Format("{0:d dd ddd dddd}", dt); // "1 01 Mon Monday" day 144 | var hour = String.Format("{0:h hh H HH}", dt); // "6 06 18 18" hour 12/24 145 | var minute = String.Format("{0:m mm}", dt); // "50 50" minute 146 | var secound = String.Format("{0:s ss}", dt); // "23 23" second 147 | var fraction = String.Format("{0:f ff fff ffff}", dt); // "2 23 230 2300" sec.fraction 148 | var fraction2 = String.Format("{0:F FF FFF FFFF}", dt); // "2 23 23 23" without zeroes 149 | var period = String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M. 150 | var zone = String.Format("{0:z zz zzz}", dt); // "+0 +00 +00:00" time zone 151 | ``` 152 | ### DateTime Formatting 153 | 154 | Different users need different kinds of format date. For instance some users need date like "mm/dd/yyyy", some need "dd-mm-yyyy". Let's say current Date Time is "12/8/2015 3:15:19 PM" and as per specifier you will get below output. 155 | ```csharp 156 | DateTime tempDate = new DateTime(2015, 12, 08); // creating date object with 8th December 2015 157 | Console.WriteLine(tempDate.ToString("MMMM dd, yyyy")); //December 08, 2105. 158 | ``` 159 | Below specifiers will help you to get the date in different formats. 160 | 161 | | Specifier | Description | Output | 162 | | --- | --- | --- | 163 | | d | Short Date | 12/8/2015 | 164 | | D | Long Date | Tuesday, December 08, 2015 | 165 | | t | Short Time | 3:15 PM | 166 | | T | Long Time | 3:15:19 PM | 167 | | f | Full date and time | Tuesday, December 08, 2015 3:15 PM | 168 | | F | Full date and time (long) | Tuesday, December 08, 2015 3:15:19 PM | 169 | | g | Default date and time | 12/8/2015 15:15 | 170 | | G | Default date and time (long) | 12/8/2015 15:15 | 171 | | M | Day / Month | 8-Dec | 172 | | r | RFC1123 date | Tue, 08 Dec 2015 15:15:19 GMT | 173 | | s | Sortable date/time | 2015-12-08T15:15:19 | 174 | | u | Universal time, local timezone | 2015-12-08 15:15:19Z | 175 | | Y | Month / Year | December, 2015 | 176 | | dd | Day | 8 | 177 | | ddd | Short Day Name | Tue | 178 | | dddd | Full Day Name | Tuesday | 179 | | hh | 2 digit hour | 3 | 180 | | HH | 2 digit hour (24 hour) | 15 | 181 | | mm | 2 digit minute | 15 | 182 | | MM | Month | 12| 183 | | MMM | Short Month name | Dec | 184 | | MMMM | Month name | December | 185 | | ss | seconds | 19 | 186 | | fff | milliseconds | 120 | 187 | | FFF | milliseconds without trailing zero | 12 | 188 | | tt | AM/PM | PM | 189 | | yy | 2 digit year | 15 | 190 | | yyyy | 4 digit year| 2015 | 191 | | : | Hours, minutes, seconds separator, e.g. {0:hh:mm:ss} | 9:08:59 | 192 | | / | Year, month , day separator, e.g. {0:dd/MM/yyyy} | 8/4/2007 | 193 | 194 | ### DateTime Parsing 195 | 196 | Sometimes we do parsing from string to DateTime object to perform operations like date difference, weekday, month name etc. For instance, there is a string value (“12/10/2015”) and our requirement is to find out weekday (Sunday or Monday and so on) of date. In this scenario we need to convert string value to DateTime object and then use WeekDay property(obj.WeekDay) to find out weekday. We can accomplish the same by built-in methods like Convert.ToDateTime(), DateTime.Parse(), DateTime.ParseExact(), DateTime.TryParse(), DateTime.TryParseExact(). Here are a few examples of how to parse a string to DateTime object: 197 | 198 | #### ParseExact 199 | ```csharp 200 | var dateString = "2015-11-24"; 201 | var date = DateTime.ParseExact(dateString, "yyyy-MM-dd", null); 202 | Console.WriteLine(date); //11/24/2015 12:00:00 AM 203 | ``` 204 | Note that passing CultureInfo.CurrentCulture as the third parameter is identical to passing null. Or, you can 205 | pass a specific culture. Input string can be in any format that matches the format string. 206 | ```csharp 207 | var date = DateTime.ParseExact("24|201511", "dd|yyyyMM", null); 208 | Console.WriteLine(date); //11/24/2015 12:00:00 AM 209 | 210 | //Case matters for format specifiers 211 | var date = DateTime.ParseExact("2015-01-24 11:11:30", "yyyy-mm-dd hh:MM:ss", null); 212 | Console.WriteLine(date); //11/24/2015 11:01:30 AM 213 | ``` 214 | Note that the month and minute values were parsed into the wrong destinations. 215 | 216 | #### TryParse 217 | This method accepts a string as input, attempts to parse it into a DateTime, and returns a Boolean result indicating 218 | success or failure. If the call succeeds, the variable passed as the out parameter is populated with the parsed result. 219 | If the parse fails, the variable passed as the out parameter is set to the default value, DateTime.MinValue. 220 | TryParse(string, out DateTime) 221 | ```csharp 222 | DateTime parsedValue; 223 | if (DateTime.TryParse("monkey", out parsedValue)) 224 | { 225 | Console.WriteLine("Apparently, 'monkey' is a date/time value. Who knew?"); 226 | } 227 | ``` 228 | This method attempts to parse the input string based on the system regional settings and known formats such as ISO 8601 and other common formats. 229 | ```csharp 230 | DateTime.TryParse("11/24/2015 14:28:42", out parsedValue); // true 231 | DateTime.TryParse("2015-11-24 14:28:42", out parsedValue); // true 232 | DateTime.TryParse("2015-11-24T14:28:42", out parsedValue); // true 233 | DateTime.TryParse("Sat, 24 Nov 2015 14:28:42", out parsedValue); // true 234 | ``` 235 | TryParse(string, IFormatProvider, DateTimeStyles, out DateTime) 236 | 237 | ```csharp 238 | if (DateTime.TryParse(" monkey ", new CultureInfo("en-GB"), 239 | DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite, out parsedValue) 240 | { 241 | Console.WriteLine("Apparently, ' monkey ' is a date/time value. Who knew?"); 242 | } 243 | ``` 244 | Unlike its sibling method, this overload allows a specific culture and style(s) to be specified. Passing **null** for the 245 | **IFormatProvider** parameter uses the system culture. 246 | 247 | Exceptions 248 | 249 | Note that it is possible for this method to throw an exception under certain conditions. These relate to the 250 | parameters introduced for this overload: **IFormatProvider** and **DateTimeStyles**. 251 | - `NotSupportedException`: `IFormatProvider` specifies a neutral culture 252 | - `ArgumentException`: `DateTimeStyles` is not a valid option, or contains incompatible flags such as 253 | `AssumeLocal` and `AssumeUniversal`. 254 | 255 | #### TryParseExact 256 | 257 | This method behaves as a combination of TryParse and ParseExact: It allows custom format(s) to be specified, and returns a Boolean result indicating success or failure rather than throwing an exception if the parse fails. 258 | **TryParseExact(string, string, IFormatProvider, DateTimeStyles, out DateTime)** 259 | This overload attempts to parse the input string against a specific format. The input string must match that format in order to be parsed. 260 | ```csharp 261 | DateTime.TryParseExact("11242015", "MMddyyyy", null, DateTimeStyles.None, out parsedValue); // true 262 | ``` 263 | **TryParseExact(string, string[], IFormatProvider, DateTimeStyles, out DateTime)** 264 | This overload attempts to parse the input string against an array of formats. The input string must match at least 265 | one format in order to be parsed. 266 | ```csharp 267 | DateTime.TryParseExact("11242015", new [] { "yyyy-MM-dd", "MMddyyyy" }, null, DateTimeStyles.None, out parsedValue); // true 268 | ``` 269 | 270 | Now a question arises in your mind, that is, why do we have so many methods for parsing? The reason is every method is for a different purpose. Use TryParse() when you want to be able to attempt a parse and handle invalid data immediately (instead of throwing the exception), and ParseExact() when the format you are expecting is not a standard format, or when you want to limit to one particular standard format for efficiency. If you're sure the string is a valid DateTime, and you know the format, you could also consider the DateTime.ParseExact() or DateTime.TryParseExact() methods. 271 | 272 | For more methods click this [link](https://docs.microsoft.com/en-us/dotnet/api/system.datetime?redirectedfrom=MSDN&view=netframework-4.8#methods). 273 | 274 | For more information about DateTime click these [link](https://docs.microsoft.com/en-us/dotnet/api/system.datetime?redirectedfrom=MSDN&view=netframework-4.8#constructors) 275 | 276 | #### Pure functions warning when dealing with DateTime 277 | 278 | Wikipedia currently defines a pure function as follows: 279 | 280 | 1. The function always evaluates the same result value given the same argument value(s). The function result 281 | value cannot depend on any hidden information or state that may change while program execution proceeds 282 | or between different executions of the program, nor can it depend on any external input from I/O devices . 283 | 284 | 2. Evaluation of the result does not cause any semantically observable side effect or output, such as mutation 285 | of mutable objects or output to I/O devices 286 | As a developer you need to be aware of pure methods and you will stumble upon these a lot in many areas. One I 287 | have seen that bites many junior developers is working with DateTime class methods. A lot of these are pure and if 288 | you are unaware of these you can be in for a suprise. An example: 289 | ```csharp 290 | DateTime sample = new DateTime(2016, 12, 25); 291 | sample.AddDays(1); 292 | Console.WriteLine(sample.ToShortDateString()); 293 | ``` 294 | Given the example above one may expect the result printed to console to be '26/12/2016' but in reality you end up with the same date. This is because AddDays is a pure method and does not affect the original date. To get the expected output you would have to modify the AddDays call to the following: 295 | ```csharp 296 | sample = sample.AddDays(1) 297 | ``` 298 | 299 | ## Complete List Of Exception Class In C# 300 | 301 | #### WHAT IS SYSTEM EXCEPTION? 302 | System Exception is predefined Exception class in C# that is ready to use in programming. Just choose which exception may occur in your code and use it in a catch block. You can use this exception for writing error free and robust code. 303 | 304 | #### System Exception 305 | | Exception| Condition | 306 | | --- | --- | 307 | | AccessViolationException | It is thrown when try to read or write protected memory. | 308 | | AggregateException | Represents one or more errors that occur during application execution. | 309 | | AppDomainUnloadedException | It is thrown when try to access an unloaded application domain. | 310 | | ApplicationException | It is base class for application-defined exceptions. | 311 | | ArgumentException | It is thrown when invalid argument provided to a method.| 312 | | ArgumentNullException | It is thrown when a method requires argument but no argument is provided.| 313 | | ArgumentOutOfRangeException | It is thrown when value of an argument is outside the allowable range.| 314 | | ArithmeticException | It is thrown when doing arithmetic, casting, or conversion operation.| 315 | | ArrayTypeMismatchException | It is thrown when try to store an element of the wrong type within an array.| 316 | | BadImageFormatException | It is thrown when file image, dll or exe program is invalid.| 317 | | CannotUnloadAppDomainException | It is thrown when try to unload an application domain fails.| 318 | | ContextMarshalException | The exception that is thrown when an attempt to marshal an object across a context boundary fails.| 319 | |DataMisalignedException|It is thrown thrown when a unit of data is read from or written to an address that is not a multiple of the data size.| 320 | |DivideByZeroException| It is thrown when there is an attempt to divide an integral or decimal value by zero.| 321 | |DllNotFoundException| It is thrown when a DLL specified in a DLL import cannot be found.| 322 | |DuplicateWaitObjectException| The exception that is thrown when an object appears more than once in an array of synchronization objects. 323 | |EntryPointNotFoundException| The exception that is thrown when an attempt to load a class fails due to the absence of an entry method.| 324 | |ExecutionEngineException| The exception that is thrown when there is an internal error in the execution engine of the common language runtime.| 325 | |FieldAccessException| It is thrown when there is an invalid attempt to access a private or protected field inside a class.| 326 | |FormatException| The exception that is thrown when the format of an argument is invalid, or when a composite format string is not well formed.| 327 | |IndexOutOfRangeException| The exception that is thrown when an attempt is made to access an element of an array or collection with an index that is outside its bounds.| 328 | |InsufficientMemoryException| The exception that is thrown when a check for sufficient available memory fails. This class cannot be inherited.| 329 | |InvalidCastException| The exception that is thrown for invalid casting or explicit conversion.| 330 | |InvalidOperationException| The exception that is thrown when a method call is invalid for the object's current state.| 331 | |InvalidProgramException| The exception that is thrown when a program contains invalid Microsoft intermediate language (MSIL) or metadata.| 332 | |InvalidTimeZoneException| The exception that is thrown when time zone information is invalid.| 333 | |MemberAccessException| The exception that is thrown when an attempt to access a class member fails.| 334 | |MethodAccessException| The exception that is thrown when there is an invalid attempt to access a method, such as accessing a private method from partially trusted code.| 335 | |MissingFieldException| The exception that is thrown when there is an attempt to dynamically access a field that does not exist.| 336 | |MissingMemberException |The exception that is thrown when there is an attempt to dynamically access a class member that does not exist.| 337 | |MissingMethodException |The exception that is thrown when there is an attempt to dynamically access a method that does not exist.| 338 | |MulticastNotSupportedException| The exception that is thrown when there is an attempt to combine two delegates based on the Delegate type instead of the MulticastDelegate type.| 339 | |NotCancelableException |It is thrown when an attempt is made to cancel an operation that is not cancelable.| 340 | |NotFiniteNumberException| The exception that is thrown when a floating-point value is positive infinity, negative infinity, or Not-a-Number (NaN).| 341 | |NotImplementedException| The exception that is thrown when a requested method or operation is not implemented.| 342 | |NotSupportedException| The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality.| 343 | |NullReferenceException| The exception that is thrown when there is an attempt to dereference a null object reference.| 344 | |ObjectDisposedException| The exception that is thrown when an operation is performed on a disposed object.| 345 | |OperationCanceledException| The exception that is thrown in a thread upon cancellation of an operation that the thread was executing.| 346 | |OutOfMemoryException| The exception that is thrown when there is not enough memory to continue the execution of a program.| 347 | |OverflowException |The exception that is thrown when an arithmetic, casting, or conversion operation in a checked context results in an overflow.| 348 | |PlatformNotSupportedException| The exception that is thrown when a feature does not run on a particular platform.| 349 | |RankException |The exception that is thrown when an array with the wrong number of dimensions is passed to a method.| 350 | |StackOverflowException| The exception that is thrown when the execution stack overflows because it contains too many nested method calls.| 351 | |SystemException| Serves as the base class for system exceptions namespace.| 352 | |TimeoutException| The exception that is thrown when the time allotted for a process or operation has expired.| 353 | |TimeZoneNotFoundException| The exception that is thrown when a time zone cannot be found.| 354 | |TypeAccessException |The exception that is thrown when a method attempts to use a type that it does not have access to.| 355 | |TypeInitializationException| The exception that is thrown as a wrapper around the exception thrown by the class initializer. This class cannot be inherited.| 356 | |TypeLoadException |The exception that is thrown when type-loading failures occur.| 357 | |TypeUnloadedException| The exception that is thrown when there is an attempt to access an unloaded class.| 358 | |UnauthorizedAccessException| The exception that is thrown when the operating system denies access because of an I/O error or a specific type of security error.| 359 | |UriFormatException|The exception that is thrown when an invalid Uniform Resource Identifier (URI) is detected.| 360 | #### System.Data Exception 361 | | Exception| Condition | 362 | | --- | --- | 363 | |ConstraintException| Represents the exception that is thrown when attempting an action that violates a constraint.| 364 | |DataException| Represents the exception that is thrown when attempting an action that violates a constraint.| 365 | |DBConcurrencyException |Gets or sets the value of the DataRow that generated the DBConcurrencyException.| 366 | |DeleteRowInaccessibleException| Represents the exception that is thrown when an action is tried on a DataRow that has been deleted.| 367 | |DuplicateNameException| Represents the exception that is thrown when a duplicate database object name is encountered during an add operation in a DataSet -related object.| 368 | |EvaluateException| Represents the exception that is thrown when the Expression property of a DataColumn cannot be evaluated.| 369 | |InRowChangingEventException| Represents the exception that is thrown when you call the EndEdit method within the RowChanging event.| 370 | |InvalidConstraintException| Represents the exception that is thrown when incorrectly trying to create or access a relation.| 371 | |InvalidExpressionException |Represents the exception that is thrown when you try to add a DataColumn that contains an invalid Expression to a DataColumnCollection.| 372 | |MissingPrimaryKeyException| Represents the exception that is thrown when you try to access a row in a table that has no primary key.| 373 | |NoNullAllowedException| Represents the exception that is thrown when you try to insert a null value into a column where AllowDBNull is set tofalse.| 374 | |OperationAbortedException| This exception is thrown when an ongoing operation is aborted by the user.| 375 | |ReadOnlyException| Represents the exception that is thrown when you try to change the value of a read-only column.| 376 | |RowNotInTableException| Represents the exception that is thrown when you try to perform an operation on a DataRow that is not in a DataTable.| 377 | |StrongTypingException| The exception that is thrown by a strongly typed DataSet when the user accesses a DBNull value.| 378 | |SyntaxErrorException |Represents the exception that is thrown when the Expression property of a DataColumn contains a syntax error.| 379 | |TypedDataSetGeneratorException| The exception that is thrown when a name conflict occurs while generating a strongly typed DataSet.| 380 | |VersionNotFoundException| Represents the exception that is thrown when you try to return a version of a DataRow that has been deleted.| 381 | #### System.IO Exception 382 | | Exception| Condition | 383 | | --- | --- | 384 | |DirectoryNotFoundException| The exception that is thrown when part of a file or directory cannot be found.| 385 | |DriveNotFoundException| The exception that is thrown when a drive that is referenced by an operation could not be found.| 386 | |EndOfStreamException| An EndOfStreamException exception is thrown when there is an attempt to read past the end of a stream.| 387 | |FileFormatException| The exception that is thrown when an input file or a data stream that is supposed to conform to a certain file format specification is malformed.| 388 | |FileLoadException| The exception that is thrown when a managed assembly is found but cannot be loaded.| 389 | |FileNotFoundException| The exception that is thrown when an attempt to access a file that does not exist on disk fails.| 390 | |InternalBufferOverflowException| The exception thrown when the internal buffer overflows.| 391 | |InvalidDataException| The exception that is thrown when a data stream is in an invalid format.| 392 | |IOException| The exception that is thrown when an I/O error occurs.| 393 | |PathTooLongException| The exception that is thrown when a path or file name is longer than the system-defined maximum length.| 394 | |PipeException| Thrown when an error occurs within a named pipe.| 395 | 396 | ## Keywords 397 | 398 | Keywords are predefined, reserved identifiers with special meaning to the compiler. They cannot be used as 399 | identifiers in your program without the @ prefix. For example @if is a legal identifier but not the keyword if. 400 | 401 | #### as 402 | 403 | The as keyword is an operator similar to a cast. If a cast is not possible, using as produces null rather than 404 | resulting in an ```InvalidCastException```. 405 | Expression ```as``` type is equivalent to expression ```is``` type ? ```(type)expression : (type)null``` with the caveat that 406 | as is only valid on reference conversions, nullable conversions, and boxing conversions. User-defined conversions 407 | are not supported; a regular cast must be used instead. For the expansion above, the compiler generates code such 408 | that expression will only be evaluated once and use single dynamic type check (unlike the two in the sample above). 409 | ```as``` can be useful when expecting an argument to facilitate several types. Specifically it grants the user multiple 410 | options - rather than checking every possibility with is before casting, or just casting and catching exceptions. It is 411 | best practice to use 'as' when casting/checking an object which will cause only one unboxing penalty. Using is to check, 412 | then casting will cause two unboxing penalties. 413 | 414 | If an argument is expected to be an instance of a specific type, a regular cast is preferred as its purpose is more 415 | clear to the reader. Because a call to as may produce null, always check the result to avoid a NullReferenceException. 416 | 417 | ```csharp 418 | object something = "Hello"; 419 | Console.WriteLine(something as string); //Hello 420 | Console.Writeline(something as Nullable); //null 421 | Console.WriteLine(something as int?); //null 422 | 423 | //This does NOT compile: 424 | //destination type must be a reference type (or a nullable value type) 425 | Console.WriteLine(something as int); 426 | ``` 427 | Equivalent example without using as: 428 | ```csharp 429 | Console.WriteLine(something is string ? (string)something : (string)null); 430 | ``` 431 | This is useful when overriding the Equals function in custom classes. 432 | ```csharp 433 | class MyCustomClass 434 | { 435 | public override bool Equals(object obj) 436 | { 437 | MyCustomClass customObject = obj as MyCustomClass; 438 | // if it is null it may be really null 439 | // or it may be of a different type 440 | if (Object.ReferenceEquals(null, customObject)) 441 | { 442 | // If it is null then it is not equal to this instance. 443 | return false; 444 | } 445 | // Other equality controls specific to class 446 | } 447 | } 448 | ``` 449 | --------------------------------------------------------------------------------