Reputation: 15239
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.
Upvotes: 5
Views: 1185
Reputation: 938
You can use an external application for this, like LINQPad:
Or the Jupyter notebook in Try .NET:
Upvotes: 0
Reputation: 2257
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] } } } }
Upvotes: 11
Reputation: 21
I have solved your issue on Visual Studio 2019 ,
first I install Microsoft.AspNetCore.Mvc.Newtonsoft.json using nuget package manager.
second using this method defined in static non generic class to dump any expression you want to verify.
public static void DumpObject(this object value)
{
Console.WriteLine(JsonConvert.SerializeObject(value, Formatting.Indented));
}
N.B: remember to add using Newtonsoft.Json;
finally form Main method invoke Class.YourDumpMethod(AnyObjToVerify); as follow:
static void Main()
{
DateTime dt = DateTime.ParseExact("2016","yyyy", null, DateTimeStyles.None);
Dump.DumpObject(dt);
int i;
bool b = int.TryParse("55", out i);
Dump.DumpObject(i);
}
Hoping it will help you
Upvotes: 0
Reputation: 1793
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
Upvotes: 3