Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 249
serge Avatar asked Jan 29 '20 10:01

serge


2 Answers

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] } } } }
like image 109
Diado Avatar answered Nov 06 '22 15:11

Diado


immediate window will not work in design mode. you need to use "C# interactive window", which is build on top of Roslyn hence install Roslyn then follow below Wiki

https://github.com/dotnet/roslyn/wiki/Interactive-Window

C# Interactive window open by below menu path:

Views > Other Windows > C# Interactive

like image 42
divyang4481 Avatar answered Nov 06 '22 15:11

divyang4481