Search code examples
c#.netvisual-studiovisual-studio-2019code-testing

Test simple c# code expressions in Visual Studio


I'd like to know how should I do to test simple C# expressions

1) in Visual Studio and
2) not in debug, in design mode

Say, I want to verify what will return this code

?DateTime.ParseExact("2016", "yyyy")

Or

int i;
int.TryParse("x55", out i);
?i

I obtained in the immediate window the following message:

?DateTime.ParseExact("2016", "yyyy") 
The expression cannot be evaluated while in design mode.

Solution

  • The Interactive Window (not to be confused with the immediate window) will achieve what you're looking for.

    It can be accessed by View > Other Windows > C# Interactive, and is essentially an interactive compiler session that runs independently of whether the project is being executed or not, allowing you to arbitrarily execute code without having to build and run your project.

    Here is an example of what can be done in this window

    > Random gen = new Random();
    > DateTime RandomDay()
    . {
    .     int monthsBack = 1;
    .     int monthsForward = 3;
    .     DateTime startDate = DateTime.Now.AddMonths(-monthsBack);
    .     DateTime endDate = DateTime.Now.AddMonths(monthsForward);    
    .     int range = (endDate - startDate).Days;
    .     return startDate.AddDays(gen.Next(range));
    . }
    > RandomDay()
    [28/01/2020 15:11:51]
    

    and also using external dlls

    > Newtonsoft.Json.Linq.JObject.Parse("{'myArticle': { 'myDate': '2020-03-24T00:00:00'}  }")
    (1,1): error CS0103: The name 'Newtonsoft' does not exist in the current context
    
    > #r "C:\Users\MyUser\.nuget\packages\newtonsoft.json\11.0.2\lib\netstandard2.0\Newtonsoft.Json.dll"
    
    > Newtonsoft.Json.Linq.JObject.Parse("{'myArticle': { 'myDate': '2020-03-24T00:00:00'}  }")
    JObject(1) { JProperty(1) { JObject(3) { JProperty(1) { [24/03/2020 00:00:00] } } } }