C Sharp: Difference between revisions

No edit summary
No edit summary
 
(4 intermediate revisions by the same user not shown)
Line 15: Line 15:
     {
     {
         // Define a regular expression for repeated words.
         // Define a regular expression for repeated words.
         Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",
         Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b");
          RegexOptions.Compiled | RegexOptions.IgnoreCase);


         // Define a test string.         
         // Define a test string.         
         string text = "The the quick brown fox  fox jumps over the lazy dog dog.";
         string text = "The the quick brown fox  fox jumps over the lazy dog dog.";
          
          
         // Find matches.
         // Find match.
         MatchCollection matches = rx.Matches(text);
         Match match = rx.Match(text);


         // Report the number of matches found.
         // Iterature through captures
         Console.WriteLine("{0} matches found in:\n  {1}",
         foreach (Capture c in match.captures) {
                          matches.Count,
          Console.WriteLine("Captured {c.Value}");
                          text);
 
        // Report on each match.
        foreach (Match match in matches)
        {
            GroupCollection groups = match.Groups;
            Console.WriteLine("'{0}' repeated at positions {1} and {2}"
                              groups["word"].Value,
                              groups[0].Index,
                              groups[1].Index);
         }
         }
     }
     }
Line 55: Line 44:
     ManualResetEvent finishedHandle = new ManualResetEvent(false);
     ManualResetEvent finishedHandle = new ManualResetEvent(false);
     for (int i = 0; i < numberOfTasks; i++) {
     for (int i = 0; i < numberOfTasks; i++) {
      // Note that you cannot reuse i here.
      // You can use this trick to put it in a closure
      // Or you can make a closure manually with another anonymous function
      // i.e. (a => { return _=>{ \\ Do stuff here })(a)
       int j = i;
       int j = i;
       ThreadPool.QueueUserWorkItem(_ => {
       ThreadPool.QueueUserWorkItem(_ => {
Line 76: Line 69:


</syntaxhighlight>
</syntaxhighlight>
==Memory Management==
C# has value types and reference types. Reference types are heap allocated similar to Java. Value types are allocated either on the stack or within objects on the heap, the same as primitives in Java or structs in C/C++.
Reference types are created with classes. Value types are created with structs.
==Platform Invoke==
[https://docs.microsoft.com/en-us/dotnet/standard/native-interop/pinvoke Reference]<br>
Platform Invoke (or P/Invoke) allows you to call and use C and C++ libraries from within your C# or other .NET programs.
[[Category:Programming languages]]