Skip to main content

C# Statements (C# Specification Part 4)

The actions of a program are expressed using statements. C# supports several different kinds of statements, a number of which are defined in terms of embedded statements.
A block permits multiple statements to be written in contexts where a single statement is allowed. A block consists of a list of statements written between the delimiters { and }.
Declaration statements are used to declare local variables and constants.
Expression statements are used to evaluate expressions. Expressions that can be used as statements include method invocations, object allocations using the new operator, assignments using = and the compound assignment operators, increment and decrement operations using the ++ and -- operators and await expressions.
Selection statements are used to select one of a number of possible statements for execution based on the value of some expression. In this group are the if and switch statements.
Iteration statements are used to repeatedly execute an embedded statement. In this group are the while, do, for, and foreach statements.
Jump statements are used to transfer control. In this group are the break, continue, goto, throw, return, and yield statements.
The try...catch statement is used to catch exceptions that occur during execution of a block, and the try...finally statement is used to specify finalization code that is always executed, whether an exception occurred or not.
The checked and unchecked statements are used to control the overflow checking context for integral-type arithmetic operations and conversions.
The lock statement is used to obtain the mutual-exclusion lock for a given object, execute a statement, and then release the lock.
The using statement is used to obtain a resource, execute a statement, and then dispose of that resource.
The following table lists C#’s statements and provides an example for each one.

Statement
Example
Local variable declaration
static void Main() {
      int a;
      int b = 2, c = 3;
      a = 1;
      Console.WriteLine(a + b + c);
}
Local constant declaration
static void Main() {
      const float pi = 3.1415927f;
      const int r = 25;
      Console.WriteLine(pi * r * r);
}
Expression statement
static void Main() {
      int i;
      i = 123;                                  // Expression statement
      Console.WriteLine(i);   // Expression statement
      i++;                                      // Expression statement
      Console.WriteLine(i);   // Expression statement
}
if statement
static void Main(string[] args) {
      if (args.Length == 0) {
            Console.WriteLine("No arguments");
      }
      else {
            Console.WriteLine("One or more arguments");
      }
}

switch statement
static void Main(string[] args) {
      int n = args.Length;
      switch (n) {
            case 0:
                  Console.WriteLine("No arguments");
                  break;
            case 1:
                  Console.WriteLine("One argument");
                  break;
            default:
                  Console.WriteLine("{0} arguments", n);
                  break;
            }
      }
}
while statement
static void Main(string[] args) {
      int i = 0;
      while (i < args.Length) {
            Console.WriteLine(args[i]);
            i++;
      }
}
do statement
static void Main() {
      string s;
      do {
            s = Console.ReadLine();
            if (s != null) Console.WriteLine(s);
      } while (s != null);
}
for statement
static void Main(string[] args) {
      for (int i = 0; i < args.Length; i++) {
            Console.WriteLine(args[i]);
      }
}
foreach statement
static void Main(string[] args) {
      foreach (string s in args) {
            Console.WriteLine(s);
      }
}
break statement
static void Main() {
      while (true) {
            string s = Console.ReadLine();
            if (s == null) break;
            Console.WriteLine(s);
      }
}
continue statement
static void Main(string[] args) {
      for (int i = 0; i < args.Length; i++) {
            if (args[i].StartsWith("/")) continue;
            Console.WriteLine(args[i]);
      }
}

goto statement
static void Main(string[] args) {
      int i = 0;
      goto check;
      loop:
      Console.WriteLine(args[i++]);
      check:
      if (i < args.Length) goto loop;
}
return statement
static int Add(int a, int b) {
      return a + b;
}
static void Main() {
      Console.WriteLine(Add(1, 2));
      return;
}
yield statement
static IEnumerable<int> Range(int from, int to) {
      for (int i = from; i < to; i++) {
            yield return i;
      }
      yield break;
}
static void Main() {
      foreach (int x in Range(-10,10)) {
            Console.WriteLine(x);
      }
}
throw and try
statements
static double Divide(double x, double y) {
      if (y == 0) throw new DivideByZeroException();
      return x / y;
}
static void Main(string[] args) {
      try {
            if (args.Length != 2) {
                  throw new Exception("Two numbers required");
            }
            double x = double.Parse(args[0]);
            double y = double.Parse(args[1]);
            Console.WriteLine(Divide(x, y));
      }
      catch (Exception e) {
            Console.WriteLine(e.Message);
      }
      finally {
            Console.WriteLine(“Good bye!”);
      }
}
checked and unchecked statements
static void Main() {
      int i = int.MaxValue;
      checked {
            Console.WriteLine(i + 1);           // Exception
      }
      unchecked {
            Console.WriteLine(i + 1);           // Overflow
      }
}

lock statement
class Account
{
      decimal balance;
      public void Withdraw(decimal amount) {
            lock (this) {
                  if (amount > balance) {
                        throw new Exception("Insufficient funds");
                  }
                  balance -= amount;
            }
      }
}
using statement
static void Main() {
      using (TextWriter w = File.CreateText("test.txt")) {
            w.WriteLine("Line one");
            w.WriteLine("Line two");
            w.WriteLine("Line three");
      }
}


Comments

Popular posts from this blog

gcAllowVeryLargeObjects Element

There are numerous new features coming with .NET 4.5 and here, on this blog, you can find several posts about it. But the feature we are goint to talk about today is very exciting, because we were waiting for it more than 10 years. Since .NET 1.0 the memory limit of .NET object is 2GB. This means you cannot for example create array which contains elements with more than 2GB in total. If try to create such array, you will get the OutOfMemoryException. Let’s see an example how to produce OutOfMemoryException. Before that Open Visual Studio 2012, and create C# Console Application, like picture below. First lets create simple struct with two double members like example below: 1 2 3 4 5 6 7 8 9 10 11 12 public struct ComplexNumber {      public double Re;      public double Im;      public ComplexNumber( double re, double im)      {          Re=re;          Im=im;      } } As we know this structure consumes about 16

Support for debugging lambda expressions with Visual Studio 2015

Anyone who uses LINQ (or lambdas in general) and the debugger will quickly discover the dreaded message “Expression cannot contain lambda expressions”. Lack of lambda support has been a limitation of the Visual Studio Debugger ever since Lambdas were added to C# and Visual Basic.  With visual studio 2015 Microsoft has added support for debugging lambda expressions. Let’s first look at an example, and then I’ll walk you through current limitations. Example To try this yourself, create a new C# Console app with this code: using System.Diagnostics; using System.Linq; class Program { static void Main() { float[] values = Enumerable.Range(0, 100).Select(i => (float)i / 10).ToArray(); Debugger.Break(); } } Then compile, start debugging, and add “values.Where(v => (int)v == 3).ToArray()” in the Watch window. You’ll be happy to see the same as what the screenshot above shows you. I am using Visual Studio 2015 Preview and it has some limitations.

How to allow a very large object in .net application?

Since .NET 1.0 the memory limit of .NET object is 2GB. This means you cannot for example create array which contains elements with more than 2GB in total. If try to create such array, you will get the OutOfMemoryException. Let’s see an example how to produce OutOfMemoryException. Before that Open Visual Studio, and create C# Console Application. Lets create simple struct with two double members like example below: public struct ComplexNumber { public double Re; public double Im; public ComplexNumber(double re, double im) { Re = re; Im = im; } } As we know this structure consumes about 16 bytes of memory. So if we want to create array of this type which consume more than 2GB we need to create array at least with 134217728 instances. So this sample program below creates 130000000 (about 1,97 GB) of array. int maxCount = 130000000; ComplexNumber[] arr = null; try { arr = new ComplexNumber[maxCount]; } catch (Exception ex) { Console.WriteLine(ex.Message); } So if we run t