Temperature Converter.

This code example shows how to:

  1. Convert Celsius to Fahrenheit
  2. Convert Fahrenheit to Celsius

View Model Code.

The view model in this example is used to display the form.

using System.ComponentModel.DataAnnotations;
namespace TempConverter.Models
{
    public class TemperatureConverterViewModel
    {
       public List Temp         { get; set; }
        [Required(ErrorMessage = "Please select a conversion option")]
        [DisplayName("Conversion Option")]
        public string ConversionType    { get; set; }
        [Required(ErrorMessage = "Please enter a starting Temperature")]
        [DisplayName("Starting Temp")]
        public string StartingTemp      { get; set; }
    }
}

Helper Class Code.

This class is used to calculate the temperatures depending on the option selected, and the starting temperature entered.

namespace TempConverter.Infrastructure
{
    public static class CalculateTemperatureHelper
    {
        public static List TempList(int value, string option)
        {
            List lstOfTemps = new List();
            switch (option)
            {
                case "1":
                    for (int i = value; i < value + 100; i += 1)
                    {
                        lstOfTemps.Add(
                            $"The temperature at {i:N}°C is {TemperatureConversionFormula.CelsiusToFahrenheit(i):N}°F");
                    }
                    break;
                case "2":
                    for (int i = value; i < 100; i += 1)
                    {
                        lstOfTemps.Add(
                            $"The temperature at {i:N}°F is {TemperatureConversionFormula.FahrenheitToCelsius(i):N}°C");
                    }
                    break;
                default:
                    lstOfTemps.Add($"The temperature conversion option you selected is not valid.");
                    break;
            }
            return lstOfTemps;
        }
        private static class TemperatureConversionFormula
        {
            public static double CelsiusToFahrenheit(int value)
            {
                return ((9.0 / 5.0) * value) + 32;
            }
            public static double FahrenheitToCelsius(int value)
            {
                return (5.0 / 9.0) * (value - 32);
            }
        }
    }
}

Home Controller code.

The home controller takes the values received from the form and passes those values to the helper class, which in turn returns the results to the controller.

using System;
using System.Collections.Generic;
using System.Web.Mvc;
using TempConverter.Infrastructure;
using TempConverter.Models;
namespace TempConverter.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            ViewBag.conversionType = LstConversionOptions();
            var model = new TemperatureConverterViewModel();
            return View("Index", model);
        }
        [HttpPost]
        public ActionResult Index(string startingTemp, string conversionType)
        {
            try
            {
                int value;
                if (!int.TryParse(startingTemp, out value))
                {
                    ModelState.AddModelError("Error", "Starting Temp can only be whole numbers");
                    ViewBag.conversionType = LstConversionOptions();
                    return View("Index");
                }
                if (ModelState.IsValid)
                {
                    var data = CalculateTemperatureHelper.TempList(Convert.ToInt32(startingTemp), conversionType);
                    var model = new TemperatureConverterViewModel
                    {
                        Temp = data
                    };
                    ViewBag.conversionType = LstConversionOptions();
                    return View("Index", model);
                }
                ViewBag.conversionType = LstConversionOptions();
                return View("Index");
            }
            catch (Exception)
            {
                ViewBag.Message = "Sorry an error has occured";
                return View("Error");
            }
        }
        private static List LstConversionOptions()
        {
            List conversionOption = new List
            {
                new SelectListItem {Text = "Convert Celsius to Fahrenheit", Value = "1"},
                new SelectListItem {Text = "Convert Fahrenheit to Celsius", Value = "2"}
            };
            return conversionOption;
        }
    }
}
Home Page Code.

The index page contains the form used to pass the data to the controller; in this example, no client-side validation is used to validate user input.

It is recommended to use client-side validation on a production site.

@model TempConverter.Models.TemperatureConverterViewModel
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
<div>
    <form action="@Url.Action("Index", "Home")" method="post">
        @Html.ValidationSummary(false)
        @Html.LabelFor(x => x.StartingTemp)<br/>
        @Html.TextBoxFor(x => x.StartingTemp)<br/>
        @Html.LabelFor(x => x.ConversionType)<br/>
        @Html.DropDownList("conversionType")<br/>
        <input type="submit" value="Convert">
    </form>
    @if(Model?.Temp != null)
    {
        <ul>
            @foreach (var t in Model.Temp)
            {
                <li>@t.ToString()</li>
            }
        </ul>
    }
</div>
</body>
</html>
Results for code.

In this short example, I showed how you could create a temperature converter in C#.

I hope you find the example helpful and if you have any comments, please use the form below.

The temperature at 1.00°C is 33.80°F
The temperature at 2.00°C is 35.60°F
The temperature at 3.00°C is 37.40°F
The temperature at 4.00°C is 39.20°F
The temperature at 5.00°C is 41.00°F
The temperature at 6.00°C is 42.80°F
The temperature at 7.00°C is 44.60°F
The temperature at 8.00°C is 46.40°F
The temperature at 9.00°C is 48.20°F
The temperature at 10.00°C is 50.00°F
The temperature at 11.00°C is 51.80°F
The temperature at 12.00°C is 53.60°F
The temperature at 13.00°C is 55.40°F
The temperature at 14.00°C is 57.20°F
The temperature at 15.00°C is 59.00°F
The temperature at 16.00°C is 60.80°F
The temperature at 17.00°C is 62.60°F
The temperature at 18.00°C is 64.40°F
The temperature at 19.00°C is 66.20°F
The temperature at 20.00°C is 68.00°F