{"id":67460,"date":"2016-08-26T14:39:32","date_gmt":"2016-08-26T14:39:32","guid":{"rendered":"https:\/\/www.simple-talk.com\/?p=67460"},"modified":"2026-04-15T18:38:53","modified_gmt":"2026-04-15T18:38:53","slug":"going-interactive-c","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/development\/dotnet-development\/going-interactive-c\/","title":{"rendered":"C# Interactive Window and .csx Scripts in Visual Studio: REPL for .NET"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\" id=\"h-executive-summary\">Executive Summary<\/h2>\n\n\n\n<p><strong>C# Interactive is a REPL (Read-Eval-Print Loop) built into Visual Studio that lets you run C# code snippets immediately without creating a project, writing a Main method, or waiting for a compile cycle. Type a line of C#, press Enter, see the result. It is particularly useful for quickly testing an API&#8217;s behaviour, exploring a new library, prototyping algorithm logic, or debugging a tricky computation interactively. C# Interactive also supports .csx script files &#8211; C# scripts that can be saved, resumed, and referenced like lightweight standalone programs. This article covers the REPL basics, the differences from standard C# compilation, .csx file workflow, assembly referencing, and a complete end-to-end example of using C# Interactive to prototype an API client.<\/strong><\/p>\n\n\n\n<p>It became easier to explore both C# code snippets and APIs with the release of Visual Studio 2015 <em>C#<\/em> <em>Interactive<\/em>, which arrived with <a href=\"https:\/\/blogs.msdn.microsoft.com\/visualstudio\/2015\/11\/30\/visual-studio-update-1-rtm\/\">Update 1<\/a>. If you think that it is just a scripting utility then it is likely that you are missing out on a valuable way of becoming more productive as a developer.<\/p>\n\n\n\n<p>It might be more accurate to classify it as C# <a href=\"https:\/\/en.wikipedia.org\/wiki\/Read%E2%80%93eval%E2%80%93print_loop\">REPL<\/a> tool with scripting support. As such, it has obvious value as a great time-saver.&nbsp;Within a REPL environment, C# developers can rapidly do such things as code prototypes, explore unfamiliar data, learn APIs and write complex tests. Readers who are familiar with languages such as F#, PowerShell and Python, already enjoy such capabilities. It\u2019s now available to the C# developer as well.<\/p>\n\n\n\n<p>This article introduces <em>C#<\/em> <em>Interactive <\/em>and aims to show how it can boost any C# developer\u2019s productivity.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-the-basics\">The Basics<\/h2>\n\n\n\n<p>Before showing how developers can take full advantage of <em>C# Interactive<\/em>, I must first cover some of the basics of getting started with <em>C# Interactive<\/em>, just in case you are new to it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-getting-started\">Getting Started<\/h3>\n\n\n\n<p><em>C#<\/em> <em>Interactive<\/em> is new to Visual Studio 2015 with Update 1. The feature can be loaded either through the <em>Developer Command Prompt for VS2015<\/em> command line and executing <em>csi.exe,<\/em> or from within the Visual Studio IDE via the menu sequence \u2018<em>View | Other Windows | C# Interactive<\/em>\u2019 as pictured below.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2016\/08\/word-image-456.png\" alt=\"\"\/><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<p>Because the Window version of <em>C# Interactive<\/em> has IntelliSense, this may be more suitable for you than the command line version. However, <em>csi.exe<\/em> has some valuable uses because, for example, it doesn\u2019t require you to load the Visual Studio IDE in order to execute C# scripts.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-life-in-a-window\">Life in a Window<\/h3>\n\n\n\n<p>C# code behaves a little differently in the <em>C# Interactive<\/em> window and some of these differences may be confusing if not frustrating. For example, you\u2019ll find that all top-level variables and members in the <em>C# Interactive <\/em>window have public modifiers by default. Although this makes sense in a REPL world, it differs from the behavior of statically complied code. You\u2019ll also find that everything executes asynchronously in the interactive mode, even if it appears to be synchronous. We\u2019ll be showing how this may require some tweaks when moving static code to the interactive window..<\/p>\n\n\n\n<p>The <a href=\"https:\/\/github.com\/dotnet\/roslyn\/wiki\/Interactive-Window\">Interactive Window<\/a> GitHub repository summarizes the features.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-csx-files\">CSX Files<\/h3>\n\n\n\n<p>When <a href=\"http:\/\/blogs.msdn.com\/b\/visualstudio\/archive\/2011\/10\/19\/introducing-the-microsoft-roslyn-ctp.aspx\">Roslyn<\/a> arrived, so did C# scripts. But until the introduction of C<em># Interactive, <\/em>scripting CSX files weren\u2019t much used. It is hardly surprising when you consider the abundance of other more widely-known and mature scripting languages such as PowerShell.<\/p>\n\n\n\n<p>This has now changed, because developers can now cut and paste code between their solution\u2019s CSX files and <em>C# Interactive<\/em> windows. This allows us to write complex snippets, saving work and rehydrating it later. It also allows us to create test cases that are executable from either Visual Studio or the command line.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"h-the-power-demonstration\">The Power Demonstration<\/h1>\n\n\n\n<p>This demonstration of the value of using<em> C# Interactive<\/em> in development is more about developing the end-to-end process. It will allow us to sketch out and assess how the process will work rather than provide the final system. <em>C# Interactive <\/em>is unlikely to impact the code that is delivered to the customer, but it can make it quicker and easier to prototype, and determine, the best solution. We\u2019ll choose a typical enterprise application assignment to show what we mean.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-getting-the-data\">Getting the Data<\/h2>\n\n\n\n<p>Imagine we have been engaged by an energy analytics provider to construct an API that allows them to access electric power consumption data that is provided by the <a href=\"http:\/\/www.eia.gov\/\">U.S. Energy Information Administration<\/a> (EIA). To get started with this exercise of prototyping a solution, we first need to complete the brief <a href=\"http:\/\/www.eia.gov\/opendata\/register.cfm\">access request<\/a> and, in turn, receive our API KEY. With this key, we then need to decide on the most appropriate http request on the <a href=\"http:\/\/www.eia.gov\/opendata\/qb.cfm?category=2122628\">Demand<\/a> page. After viewing a few series, we choose to select the <a href=\"http:\/\/www.eia.gov\/opendata\/qb.cfm?category=2122628&amp;sdid=EBA.PGE-ALL.D.H\">Demand for Portland General Electric Company, Hourly<\/a> dataset:<\/p>\n\n\n<div class=\"block-core-list\">\n<ol class=\"wp-block-list\">\n<li><a href=\"http:\/\/api.eia.gov\/series\/?api_key=YOUR_API_KEY_HERE&amp;series_id=EBA.PGE-ALL.D.H\">http:\/\/api.eia.gov\/series\/?api_key=YOUR_API_KEY_HERE&amp;series_id=EBA.PGE-ALL.D.H<\/a><\/li>\n<\/ol>\n<\/div>\n\n\n<div class=\"note\">\n<p class=\"note\"><em>Note:<\/em> Readers wishing to learn more about the EIA API may find their BETA User Guide helpful.<\/p>\n<\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-building-the-solution\">Building the Solution<\/h2>\n\n\n\n<p>We\u2019ll start off by using conventional C#. The solution starts out with the <strong><em>DemoLibrary<\/em><\/strong> component referenced and called by a console consumer entitled <strong><em>DemoClient<\/em>.<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2016\/08\/word-image-457.png\" alt=\"\"\/><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<p><strong><em>GetDemandRaw<\/em><\/strong> walks a familiar path for executing an asynchronous http get request. The method leverages the <em>System.Net.Http<\/em>\u2019s <em>HttpClient<\/em> to execute our demand query laced via string interpolation with the target company\u2019s <strong><em>seriesId<\/em><\/strong> and API key that we obtained earlier from the EAI. Our secret API key is saved in the library because at this stage we are just prototyping.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">using System.Net.Http;\nusing System.Threading.Tasks;\n\nnamespace DemoLibrary\n{\n&nbsp;&nbsp;&nbsp; public static class EnergyData\n&nbsp;&nbsp;&nbsp; {\n\/\/ Running this code requires replacing \"YOUR REQUESTED KEY\" with a key\n\/\/ obtained from U.S. Energy Information Administration.\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; private const string ApiKey = \"YOUR REQUESTED KEY\";\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/\/ &lt;summary&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/\/ Data Source: U.S. Energy Information Administration; see http:\/\/www.eia.gov\/.\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/\/ &lt;\/summary&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public static async Task&lt;string&gt; GetDemandRaw(string seriesId)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; using (var httpClient = new HttpClient())\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {\n                var response = await httpClient.GetAsync(\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$\"http:\/\/api.eia.gov\/series\/?api_key={ApiKey}&amp;series_id={seriesId}\");\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return await response.Content.ReadAsStringAsync();\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }\n&nbsp;&nbsp;&nbsp; }\n}\n<\/pre>\n\n\n\n<p>The consuming <strong><em>Main<\/em><\/strong> method in <strong><em>DemoClient<\/em><\/strong> indicates that our handiwork proved adequate as shown by the displayed JSON when we execute the compiled command-line program.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">using System;\nusing System.Linq;\nusing DemoLibrary;\n\nnamespace DemoClient\n{\n&nbsp;&nbsp;&nbsp; public class Program\n&nbsp;&nbsp;&nbsp; {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public static void Main(string[] args)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/ Demand for Portland General Electric Company\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; const string seriesId = \"EBA.PGE-ALL.D.H\";\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var energyDemandRaw = EnergyData.GetDemandRaw(seriesId).Result;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Console.WriteLine(\"Raw Data:\");\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Console.WriteLine(energyDemandRaw.Substring(1, 1000) + \"...\");\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Console.ReadKey();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }\n&nbsp;&nbsp;&nbsp; }\n}<\/pre>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2016\/08\/word-image-458.png\" alt=\"\"\/><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<p>Well, there the story could easily end without the need for any more significant development work. However, while we are packing up our laptop for the next assignment, the client\u2019s development team reports dismay. They do not like the JSON data provided by <strong><em>GetDemandRaw<\/em><\/strong>. They expected a more digestible .NET version of the data as .NET objects.<\/p>\n\n\n\n<p><strong><em>GetDemand<\/em><\/strong> reflects that wish. Someday it will return a list of lightweight <strong><em>EnergyDemand<\/em><\/strong> objects, until then we will settle for an empty one.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp;&nbsp;&nbsp; public class EnergyDemand\n&nbsp;&nbsp;&nbsp; {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public string ReportDateTime { get; set; }\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public int Demand { get; set; }\n&nbsp;&nbsp;&nbsp; }\n\n&nbsp;&nbsp;&nbsp; public static IEnumerable&lt;EnergyDemand&gt; GetDemand(string seriesId)\n&nbsp;&nbsp;&nbsp; {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/ TODO\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return Enumerable.Empty&lt;EnergyDemand&gt;();\n&nbsp;&nbsp;&nbsp; }<\/pre>\n\n\n\n<p>It\u2019s at this stage that the development process begins to crawl. While some may find converting raw JSON into a list of .NET objects institutively obvious, others (like me) do not. Traditionally we\u2019d be faced with checking debugger state, probing in the <em>Intermediate<\/em> window, tweaking code, recompiling the solution, reloading data, either directly or in directly, until happy. It\u2019s not an insurmountable process, just tedious and slow. Time for <em>C# Interactive<\/em>!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-exploring\">Exploring<\/h2>\n\n\n\n<p>We will now switch to using C# Interactive. The process of executing code in <em>C#<\/em> <em>Interactive <\/em>does not differ much from that of a console application. The first difference is in telling it how to load <strong><em>DemoLibrary<\/em><\/strong><em>.<\/em> Once that\u2019s done, we just copy the <strong><em>DemoClient<\/em><\/strong> code into the window as shown below.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2016\/08\/word-image-459.png\" alt=\"\"\/><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<p>An odd thing happens after we enter the last line of code; odd in that nothing happens. The window just sits. Did we forget that <em>C# Interactive<\/em> executes asynchronously while looking synchronous? With that detail in mind a fix becomes obvious. <strong><em>GetDemandRaw<\/em><\/strong> needs \u201cprompting\u201d before yielding any secrets as the revised code shows.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2016\/08\/word-image-460.png\" alt=\"\"\/><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<p>Now the fun, in terms of productivity, begins. We can explore the <strong><em>energyDemandRaw<\/em><\/strong> object without reloading it or recompiling any code. All we need to do to convert the output JSON string into a dynamic object is to load a <strong><em>serializer<\/em><\/strong>. While many libraries serve this function, we keep it simple by using the readily available .NET library, <em>System.Web.Script.Serialization<\/em>.<\/p>\n\n\n\n<p>Loading <em>System.Web.Script.Serialization<\/em> follows a similar pattern to the <strong><em>DemoLibrary<\/em><\/strong> component. The difference is that we do not specify a file path. After we have created the <strong><em>serializer<\/em><\/strong>, we can now explore data with C# as a familiar object-oriented workout. For example, as shown below, after we discover that <strong><em>energyDemand<\/em><\/strong> is a dictionary, then the process of identifying keys only requires a C# <em>foreach<\/em> loop.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2016\/08\/word-image-461.png\" alt=\"\"\/><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-saving-progress\">Saving Progress<\/h2>\n\n\n\n<p>How can we save our work in progress? Imagine that we\u2019ve just been asked to pause working on our current chore in order to address a late-breaking emergency. We have a slight problem though. How do we avoid losing what we just learned about the demand output? Where should we safely save the code snippet? There are some rather awkward-seeming choices such as saving it to DropBox in a text file or hiding it in the library. There\u2019s now a better option \u2013 adding it to a C# script file.<\/p>\n\n\n\n<p>In order to save code with the <em>C# Interactive<\/em> feature, all we need to do is to create a CSX file as noted earlier. Unfortunately, Visual Studio does not make this easy because we have to add the file and change its extension to CSX. Once we\u2019ve done this, we can paste code into it from the <em>C# Interactive <\/em>window.<\/p>\n\n\n\n<p>In order to save our work, we create the <em>CreateGetDemand.csx<\/em> file and copy the REPL code onto it. Sadly, pesky red squiggles on lines 9 and 10 inform us of some code issues.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2016\/08\/word-image-462.png\" alt=\"\"\/><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<p>We again encounter one of those quirks that come about because C# lives in slighty different environments. CSX files behave more like compiled code and less like its REPL brethern. In this instance the fix only requires us to move the offending lines to top of the file as suggested by Visual Studio.<\/p>\n\n\n\n<p>The fixed <em>CreateGetDemand.csx<\/em> that follows now displays without error.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#r \"System.Web.Extensions\"\n#r \".\\bin\\Debug\\DemoLibrary.dll\"\n\nusing DemoLibrary;\nusing System.Web.Script.Serialization;\n\nconst string seriesId = \"EBA.PGE-ALL.D.H\";\nvar energyDemandRaw = (await EnergyData.GetDemandRaw(seriesId));\nConsole.WriteLine(energyDemandRaw.Substring(1, 100) + \"...\");\n\nvar serializer = new JavaScriptSerializer();\nvar energyDemand = serializer.Deserialize&lt;dynamic&gt;(energyDemandRaw);\nConsole.WriteLine(energyDemand.GetType());\n\nforeach (string s in energyDemand.Keys)\n&nbsp;&nbsp;&nbsp; Console.WriteLine(s);<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-resuming\">Resuming<\/h2>\n\n\n\n<p>Our imaginary emergency passes. How do we resume where we left off, deciphering JSON output in order to complete <strong><em>GetDemand<\/em><\/strong>? The value of having saved our prototype work to a C# script file now becomes evident. We effortlessly reload it into an open <em>C# Interactive <\/em>with the following command.<\/p>\n\n\n\n<p>#load &#8220;C:\\Temp\\DemoScript\\DemoLibrary\\CreateGetDemand.csx&#8221;<\/p>\n\n\n\n<p>The window shows that we have reconstituted <strong><em>energyDemand<\/em><\/strong><em>. This can be seen <\/em>in the <strong><em>series<\/em> <\/strong>value assignment that follows it, and our subsequent proddings.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2016\/08\/word-image-463.png\" alt=\"\"\/><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<p>We continue to determine object types, and inspecting values, until we are satisfied that we have a set of data for the Portland General Electric Company\u2019s hourly power-demand.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2016\/08\/word-image-464.png\" alt=\"\"\/><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<p>We update <em>CreateGetDemand.csx<\/em> to record how we unwrapped the JSON document.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#r \"System.Web.Extensions\"\n#r \".\\bin\\Debug\\DemoLibrary.dll\"\nusing System.Web.Script.Serialization;\nusing DemoLibrary;\n\nconst string seriesId = \"EBA.PGE-ALL.D.H\";\nvar energyDemandRaw = (await EnergyData.GetDemandRaw(seriesId));\nConsole.WriteLine(energyDemandRaw.Substring(1, 100) + \"...\");\n\nvar serializer = new JavaScriptSerializer();\nvar energyDemand = serializer.Deserialize&lt;dynamic&gt;(energyDemandRaw);\nConsole.WriteLine(energyDemand.GetType());\n\nforeach (string s in energyDemand.Keys)\n&nbsp;&nbsp;&nbsp; Console.WriteLine(s);\n\nvar series = energyDemand[\"series\"];\nConsole.WriteLine(series.GetType());\n\nvar seriesDataSet = series[0];\nConsole.WriteLine(seriesDataSet.GetType());\n\nforeach (var item in seriesDataSet)\n&nbsp;&nbsp;&nbsp; Console.WriteLine(string.Format(\"{0} - {1}\", item.Key, item.Value));\nvar data = seriesDataSet[\"data\"];\nforeach (var item in data)\n{\n&nbsp;&nbsp;&nbsp; if (item[1] != null)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Console.WriteLine(string.Format(\"{0} - {1}\", item[0], item[1]));\n}<\/pre>\n\n\n\n<p>With this prototyping code, our implementation of <strong><em>GetDemand<\/em> <\/strong>can proceed quickly. We start by adding the <em>Microsoft.CSharp<\/em> and <em>System.Web.Extensions<\/em> component references to the solution.<\/p>\n\n\n\n<div class=\"note\">\n<p class=\"note\"><em>Note:<\/em>Microsoft.CSharp helps read the serialized object that System.Web.Extensions created. C# Interactive did not require it for reasons that we will cover shortly.<\/p>\n<\/div>\n\n\n\n<p>Notice how our investigatory REPL eased the <strong><em>data<\/em><\/strong> variable assignment. Transitioning from the complex JSON string in <strong><em>energyDemandRaw<\/em><\/strong> to <strong><em>data<\/em><\/strong> (almost) makes us look like EIA API experts.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public static IEnumerable&lt;EnergyDemand&gt; GetDemand(string seriesId)\n{\n&nbsp;&nbsp;&nbsp; var energyDemandRaw = GetDemandRaw(seriesId).Result;\n\n&nbsp;&nbsp;&nbsp; var serializer = new JavaScriptSerializer();\n&nbsp;&nbsp;&nbsp; var energyDemand = serializer.Deserialize&lt;dynamic&gt;(energyDemandRaw);\n\n&nbsp;&nbsp;&nbsp; var data = energyDemand[\"series\"][0][\"data\"];\n\n&nbsp;&nbsp;&nbsp; foreach (var item in data)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (item[1] != null)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; yield return new EnergyDemand { ReportDateTime = item[0], Demand = item[1] };\n}<\/pre>\n\n\n\n<p>After updating <strong>DemoClient <\/strong>to call <strong>GetDemand<\/strong>, we see everything behaving as expected.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public static void Main(string[] args)\n{\n&nbsp;&nbsp;&nbsp; \/\/ Demand for Portland General Electric Company\n&nbsp;&nbsp;&nbsp; const string seriesId = \"EBA.PGE-ALL.D.H\";\n&nbsp;&nbsp;&nbsp; var energyDemandRaw = EnergyData.GetDemandRaw(seriesId).Result;\n&nbsp;&nbsp;&nbsp; Console.WriteLine(\"Raw Data:\");\n&nbsp;&nbsp;&nbsp; Console.WriteLine(energyDemandRaw.Substring(1, 1000) + \"...\");\n\n&nbsp;&nbsp;&nbsp; Console.WriteLine();\n\n&nbsp;&nbsp;&nbsp; var energyDemandList = EnergyData.GetDemand(seriesId);\n&nbsp;&nbsp;&nbsp; Console.WriteLine(\"Enumerable&lt;EnergyDemand&gt;:\");\n&nbsp;&nbsp;&nbsp; foreach (var energyDemand in energyDemandList.Take(5))\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Console.WriteLine(\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $\"{energyDemand.ReportDateTime} | {energyDemand.Demand}\");\n\n&nbsp;&nbsp;&nbsp; Console.ReadKey();\n}<\/pre>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2016\/08\/word-image-465.png\" alt=\"\"\/><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<p>Only one problem remains. How can we more thoroughly test our API?<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-testing\">Testing<\/h2>\n\n\n\n<p>For testing<em>, C# Interactive<\/em> can to the rescue again! After writing some test code via REPL we add it the following <strong><em>TestGetDemand.<\/em>c<em>sx<\/em><\/strong> file. While the tests are far from rigorous, they do check a few different companies and some different values. It also allows us to alter and add new tests as warranted.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#r \"System.Core\"\n#r \".\\bin\\Debug\\DemoLibrary.dll\"\n#r \".\\bin\\Debug\\DemoLibrary.dll\"\nusing System.Threading.Tasks;\nusing DemoLibrary;\n\n\/\/ Arizona Public Service Company\nvar seriesId = \"EBA.AZPS-ALL.D.H\";\nawait Task.Run(() =&gt;\n&nbsp;&nbsp;&nbsp; Console.WriteLine(\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \"SeriesId \" + seriesId + \" record count: \" +\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; EnergyData.GetDemand(seriesId).Count()));\n\n\/\/ Los Angeles Department of Water and Power\nseriesId = \"EBA.LDWP-ALL.D.H\";\nawait Task.Run(() =&gt;\n&nbsp;&nbsp;&nbsp; Console.WriteLine(\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \"SeriesId \" + seriesId + \" first ReportDateTime: \" +\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; EnergyData.GetDemand(seriesId).First().ReportDateTime));\n\n\/\/ Portland General Electric Company\nseriesId = \"EBA.PGE-ALL.D.H\";\nawait Task.Run(() =&gt;\n&nbsp;&nbsp;&nbsp; Console.WriteLine(\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \"SeriesId \" + seriesId + \" maximum Demand: \" +\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; EnergyData.GetDemand(seriesId)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .OrderByDescending(x =&gt; x.Demand).FirstOrDefault().Demand));<\/pre>\n\n\n\n<p>Another bonus of having a CSX script file is that there are options for running it. Earlier we saw how they can be executed in a <em>C# Interactive<\/em> window. This time we run it via Developer Command Prompt for VS2015 by calling <strong>csi.exe<\/strong> with the link to the script file as a parameter.<\/p>\n\n\n\n<p><code>C:\\Temp\\DemoScript\\DemoLibray&gt;csi TestGetDemand.csx<\/code><\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2016\/08\/word-image-466.png\" alt=\"\"\/><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<p>The demonstration\u2019s solution as shown below is completed. Our imaginary energy analytics company developers can now obtain the data from the U.S. Energy Information Administration API, formatted just as they wanted it.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2016\/08\/word-image-467.png\" alt=\"\"\/><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-referencing\">Referencing<\/h2>\n\n\n\n<p>It is sometimes confusing to figuring out references when working within <em>C# Interactive<\/em>. For example, has anyone <em>who<\/em> is reading this noticed that the REPL code never included the obligatory <em>System <\/em>enabling <em>Console.WriteLine<\/em>? Nonetheless, it certainly does write. Turns out that <em>C# Interactive<\/em> creates and manages its own environment as evidenced by the second line that is displayed after first loading the window.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2016\/08\/word-image-468.png\" alt=\"\"\/><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<p>A quick visit to the <a href=\"https:\/\/github.com\/dotnet\/roslyn\">Roslyn<\/a> GitHub site informs us that <em>CSharpInteractive.rsp<\/em> loads three components: <em>System<\/em>, <em>System.Core<\/em>, and <em>Microsoft.CSharp.<\/em> (Remember that we had to manually add it to our solution for <strong><em>GetDemand<\/em><\/strong>?) It also takes care of inserting several common <em>using<\/em> statements.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"h-conclusion\">Conclusion<\/h1>\n\n\n\n<p>With <em>Interactive C#, d<\/em>evelopers are no longer constrained to statically-compiled code. They can now apply their .NET expertise within scripting and REPL environments. Unfortunately, these different environments are not completely compatible with each other and Visual Studio only offers some help to address the incompatibilities. Nonetheless, .NET developers comfortable with <em>Interactive C# <\/em>are likely to find themselves writing code faster and having more fun doing so.<\/p>\n\n\n\n<section id=\"faq\" class=\"faq-block my-5xl\">\n    <h2>FAQs: Going Interactive with C#<\/h2>\n\n                        <h3 class=\"mt-4xl\">1. What is C# Interactive in Visual Studio?<\/h3>\n            <div class=\"faq-answer\">\n                <p>C# Interactive is a REPL (Read-Eval-Print Loop) available in Visual Studio through View &gt; Other Windows &gt; C# Interactive. It evaluates C# expressions and statements immediately and prints results &#8211; no project, no compilation step, no Main method. You can reference NuGet packages with #r &#8220;nuget: PackageName&#8221;, load other .csx files with #load, and interact with objects across multiple lines as if in a persistent session. It is the same Roslyn-based engine used by .NET Interactive (Jupyter notebooks for .NET).<\/p>\n            <\/div>\n                    <h3 class=\"mt-4xl\">2. What are .csx files in C#?<\/h3>\n            <div class=\"faq-answer\">\n                <p>.csx files are C# script files &#8211; C# code that runs as a script rather than as compiled assembly. Unlike standard .cs files, .csx files don&#8217;t require a namespace, class, or Main method &#8211; code at the top level executes directly. They support #r for assembly\/NuGet references and #load for including other .csx files. Run them with the dotnet-script tool (dotnet tool install -g dotnet-script) or execute them from C# Interactive with #load. They are useful for automation scripts, utility tools, and prototyping where a full project is overkill.<\/p>\n            <\/div>\n                    <h3 class=\"mt-4xl\">3. How is C# Interactive different from LINQPad?<\/h3>\n            <div class=\"faq-answer\">\n                <p>LINQPad is a separate third-party application (with free and paid tiers) that provides a richer REPL experience than C# Interactive: multi-tab sessions, built-in database query connections, a NuGet package manager GUI, and result visualisation. C# Interactive is built into Visual Studio at no extra cost and integrates directly with the current solution (giving access to types from loaded projects). For quick exploration within a Visual Studio project, C# Interactive is more convenient. For standalone data exploration or database querying, LINQPad&#8217;s additional features are valuable.<\/p>\n            <\/div>\n                    <h3 class=\"mt-4xl\">4. Can I use .NET Interactive notebooks instead of C# Interactive?<\/h3>\n            <div class=\"faq-answer\">\n                <p>.NET Interactive notebooks (available through VS Code with the Polyglot Notebooks extension or Jupyter with the .NET kernel) are the evolution of the C# scripting concept &#8211; supporting C#, F#, PowerShell, and SQL in the same notebook, with rich output formatting and inline visualisation. For documentation, teaching, or exploratory analysis where you want to share the code and its output, .NET Interactive notebooks are more powerful than .csx files. For quick in-Visual Studio prototyping, C# Interactive remains the faster tool.<\/p>\n            <\/div>\n            <\/section>\n","protected":false},"excerpt":{"rendered":"<p>C# Interactive Window and .csx script files let you explore .NET APIs and prototype code without a full compile-run cycle. Covers the REPL basics, saving work as .csx files, referencing assemblies, and a practical API exploration workflow.&hellip;<\/p>\n","protected":false},"author":200451,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":true,"footnotes":""},"categories":[143538],"tags":[],"coauthors":[17935],"class_list":["post-67460","post","type-post","status-publish","format-standard","hentry","category-dotnet-development"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/67460","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/200451"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=67460"}],"version-history":[{"count":9,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/67460\/revisions"}],"predecessor-version":[{"id":109808,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/67460\/revisions\/109808"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=67460"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=67460"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=67460"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=67460"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}