Help needed with C#

Hey, I just started learning c# and I wanted to know if there is a way to check if a user enters the right thing.

For e.g. The program asks for a string but an integer is enter. How would I go about checking the validity of the input?

C# is strongly typed so you should give a try at parsing the data. There are objects in C# that represent primitive types. Actually their name correspond the the .NET types. For instance int is Int32. Those objects have methods such as Parse or TryParse. There is also a Convert object.

Here some docs:


1 Like

The case of an integer being entered when you wanted a “string” is a tricky one because you can have strings like “1”. You may need to use a regex library to do further data validation (eg. to make sure the string only contains alphabetic characters and whitespace).

1 Like

Oh man reading again I realise I completely did not understand the question. Sorry for that.

Depends on application type. I don’t know how to validate data outside of ASP. It is explained in the ASP course should you follow it.
I did not do such thing in XAML based applications such as WPF or Xamarin /.NET MAUI but there seem to be a way around that.

Validation in XAML based apps

1 Like

I tried using the int.parse and it worked. Thanks guys.