C# Exercises

Home AgriMetSoft About Contact

Short Hand If Technique in C#

	    
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace If_Short_Hand
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void short_if_Click(object sender, EventArgs e)
    {
      // Syntax
      // variable = (condition) ? if body : else body;

      // Sample
      var a = 2.3;
      var a1 = a > 2 ? true : false;
      var a2 = a > 2 ? "true" : "false";
      // c# if shorthand without else
      var a3 = a < 2 ? "true" : null;
      var a4 = a < 2 ? "true" : default(string);
      // Its application
      double[] arr = new double[] { 1.2, 2.3, 3.5, 1.5, 1.6, 2.4, 1.8 };
      var max1 = arr.Select(v => v > 2 ? 1 : -1).ToArray();
      var max2 = arr.Select(v => v > 2 ? 1 : -1).ToArray().Where(u => u > 0).ToArray();
      var max3 = arr.Select((v, i) => v > 2 ? i : -1).ToArray().Where(u => u > 0).ToArray();
      var max4 = arr.Select((v, i) => v == arr.Max() ? i : -1).ToArray().Where(u => u > 0).ToArray();
    }
  }
}
		
	 


Download the project of Visual Studio 2013 in DropBox Download


The Little-Known Short Hand If Technique in C# You've Been Missing Out On!


List of Exercises